Вопрос

I'm am trying to use SQLClient for Entity Framework functions, but I'm having some issues. I need to convert ID (which in the database is a an int) to a nvarchar so that I can compare it using wildcards.

This works to an extent (i.e. it builds and executes without erroring), however it's not what I need to do as db side, it returns the wrong results. In fact, it returns 0 rows, when it should be returning a number.

return "SqlServer.STR(ID) LIKE '824%'";

The above line basically translates to the below line in SQL

SELECT COUNT(*) FROM Table1 WHERE STR(ID) LIKE '824%' 

What I need in SQL is the following line (or something similar) because this returns the correct number of rows.

SELECT COUNT(*) FROM Table1 WHERE CONVERT(NVARCHAR(50), ID) LIKE '824%'

I've tried using:

return "CAST(ID AS NVARCHAR(50)) LIKE '824%'";

But this gives the following error at runtime:

Type 'NVARCHAR' could not be found. Make sure that the required schemas are loaded and that the namespaces are imported correctly.

Can anyone tell me how to do this using SqlClient string functions, or some other variant?

Thanks all.

Это было полезно?

Решение

You can using the SqlFunction.StringConvert() function. There is no overload for int, so you have to type cast

var test = dataContext.Table1
                      .Where(f => SqlFunctions.StringConvert((double) f.Id)
                                               .Trim()
                                               .StartsWith("824"))
                      .Select(f => SqlFunctions.StringConvert((double) f.Id)
                                               .Trim())
                      .ToList();

This will be converted as

SELECT 
LTRIM(RTRIM(STR( CAST( [Extent1].[Id] AS float)))) AS [C1]
FROM [dbo].[Table1] AS [Extent1]
WHERE (LTRIM(RTRIM(STR( CAST( [Extent1].[Id] AS float)))) LIKE N'4%')
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top