EF Core Function to Pass "AS" in `CAST( 'value' AS VARCHAR(1024))`
Asked Answered
M

1

3

I have a piece of code in EF Core that looks like this:

var queryPart1 = from table1 in context.Table1
                 select table1.ColA;

var queryPart2 = from table2 in context.Table2
                 select table2.ColX;

var finalQuery = queryPart1.Union(queryPart2);

var result = await finalQuery.ToListAsync(cancellationToken);

Of course my real code is a bit more complex, but the idea is that EF does not like the Union here because although ColA and ColX are both strings, they have different length.

I'm guessing the right way to solve this is to CAST both of them to the length of the longest column or something like that. But I do not want to write the whole query in T-SQL as the it's a bit more complicated than above and could really use LINQ.

I couldn't find a built-in EF Core function that does that when both "from" and "to" types are strings (it does it if you for example cast a string to a date). I tried to do something like .Substring(0, 1024) but it did not work.

I looked into mapping custom function. It might be easy to translate something like
context.Cast("table1.ColX", "VARCHAR(1024)") to something like
CAST(table1.ColX, 'VARCHAR(1024)'). But this is "not" the correct syntax for CAST.

The correct syntax is CAST(table1.ColX AS VARCHAR(1024)).
Note the AS VARCHAR(1024) bit.

How would I write an EF Core to SQL function translation that does that?

Note: ideally the whole bit VARCHAR(1024) would be passed as a variable.

Midriff answered 26/6, 2022 at 0:51 Comment(2)
Convert() is the same as Cast in t-sql but with a function-like style.Boracic
I don't know much about EF, but you may try to use nested queries SELECT colx AS coly FROM (SELECT CAST(colx AS VARCHAR);Evieevil
A
5

Try Convert.ToString(x) it translates to Convert(nvarchar(max), x)

If it doesn't work you will need to make the join in the runtime.

You could also create a View.

Auric answered 26/6, 2022 at 5:31 Comment(1)
This is awesome. It does not answer the literal question but it did solve my problem. Thanks a lot.Midriff

© 2022 - 2024 — McMap. All rights reserved.