Linq function such as .Net string.CompareOrdinal

I need to compare strings using string.CompareOrdinal(...) inside linq query.

 string max; string min; var res = db.Table .Where(c => string.CompareOrdinal(c.Id, min) >= 0) .Where(c => string.CompareOrdinal(c.Id, max) <= 0) .ToList(); 

The code throws an exception:

LINQ ti Entities do not reconstruct the 'Int32 CompareOrdinal (System.String, System.String)' method, and this method cannot be translated into a storage expression.

There is a lot of data in the table, so I really need a where clause.

Is there any way around this?

Update

I do not try if the two lines are equal - case sensitive or not.

I am trying to determine if a string is within range. So quistion

  • Is there a way to do this - does it work with L2E?

Obviously I cannot use string.CompareOrdinal

+4
source share
2 answers

My colleague found a workaround using string.Compare instead of string.CompareOrdinal

 string min = "a"; string max = "z"; var res = db.Table .Where(c => string.Compare(c.Id, min, StringComparison.OrdinalIgnoreCase) >= 0) .Where(c => string.Compare(c.Id, max, StringComparison.OrdinalIgnoreCase) <= 0) .ToList(); 

this is the generated SQL:

 SELECT [Extent1].[Id] AS [Id] FROM [dbo].[Table] AS [Extent1] WHERE ([Extent1].[Id] >= 'a') AND ([Extent1].[Id] <= 'z') 
+6
source

If Id is a string, this solution works, so it looks like Id is an int. Int cannot be compared to a string. Change Id to string or min / max to int to make it work (and use a simple <and> between int values).

By the way: it would save 1 iteration to check min and max at 1, where is the function.

0
source

All Articles