views:

137

answers:

2

This isn't a case-sensitive comparison in Linq to entities:

Thingies.First(t => t.Name == "ThingamaBob");

How can I achieve case sensitive comparison with Linq to entities?

+8  A: 

That's because you are using LINQ To Entities which is ultimately convert your Lambda Expressions into SQL statements. That means the case sensitivity is at the mercy of your SQL Server which by default has SQL_Latin1_General_CP1_CI_AS Collation and that is NOT case sensitive.

Using ObjectQuery.ToTraceString to see the generated SQL query that has been actually submitted to SQL Server reveals the mystery:

string sqlQuery = ((ObjectQuery)context.Thingies
        .Where(t => t.Name == "ThingamaBob")).ToTraceString();


When you create a LINQ to Entities query, LINQ to Entities leverages the LINQ parser to begin processing the query and converts it into a LINQ expression tree. The LINQ expression tree is then passed to Object Services API, which converts the expression tree to a command tree. It is then sent to the store provider (e.g. SqlClient), which convert the command tree into the native database command text. Query get executed on the data store and the results are Materialized into Entity Objects by Object Services. No logic has been put in between to take case sensitivity into account.So no matter what case you put in your predicate, it will always treat as the same by your SQL Server unless you change your Sql Server Collates for that column.

Server side solution:
Therefore, the best solution would be to change the Collation of the Name column in Thingies table to COLLATE Latin1_General_CS_AS which is case sensetive by running this on your Sql Server:

ALTER TABLE Thingies
ALTER COLUMN Name VARCHAR(25)
COLLATE Latin1_General_CS_AS

For more information on the Sql Server Collates, take a a look at SQL SERVER – Collate – Case Sensitive SQL Query Search

Client side solution:
The only solution that you can apply on client side is to use LINQ to Objects to do yet another comparison which doesn't seem to be very elegant:

Thingies.First(t => t.Name == "ThingamaBob")
        .AsEnumerable()
        .FirstOrDefault(t => t.Name == "ThingamaBob");
Morteza Manavi
I am generating the database schema with Entity Framework, so a solution using my calling code would be best. I guess I will do a check after the results have come back. Thanks.
Ronnie Overby
No problem. Yes, that is correct and I've updated my answer with a client side solution, however it isn't very elegant and I still recommend to use the data store solution.
Morteza Manavi
A: 

Have a look at the last answer on This page. It applies to L2Sql but i believe it will also work in L2E although I have not tried it yet.

I don't see a way to set this in EF.
Ronnie Overby