LINQ到实体区分大小写的比较大小写、实体、LINQ

2023-09-02 21:07:58 作者:笑看浮华苍生

这是不是在LINQ的区分大小写的比较实体:

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

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

我怎样才能实现与LINQ到实体区分大小写的比较?

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

推荐答案

那是因为你使用的 LINQ到实体的是最终将您的lambda前pressions到SQL语句。这意味着大小写是在您的SQL Server的摆布它默认有 SQL_Latin1_General_CP1_CI_AS 的排序规则,并且不区分大小写。 使用的 ObjectQuery.ToTraceString 的看到,实际上已经提交到SQL Server生成的SQL查询,揭示了谜底:

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();

当您创建的 LINQ到实体的查询, LINQ到实体的利用了LINQ解析器开始处理查询,并将其转换成一个LINQ EX pression树。在LINQ EX pression树,然后传递到的的 对象服务 的的API,其中前pression树转换到命令树。然后将其发送到存储提供商(如使用SqlClient),其中转换命令树到本地数据库命令文本。查询的数据存储得到执行和结果的实体的成的实体对象的通过的对象服务的。没有逻辑已投入之间采取区分大小写到account.So不管你放什么情况下你的predicate,它会永远一概而论通过您的SQL Server,除非你改变你的SQL服务器核对该列。 服务器端解决方案: 因此,最好的解决办法是改变的的名称排序规则的列中的一样的东西的表整理 Latin1_General_CS_AS 这区分sensetive通过SQL服务器上运行此:

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

有关的 Sql Server的整理的,采取AA看的 SQL SERVER - 分页 - 区分大小写的SQL查询搜索的 客户端解决方案: 您可以在客户端应用的唯一解决办法是使用的的LINQ to对象的做但它似乎并不很优雅的另一种比较:

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.Where(t => t.Name == "ThingamaBob")
        .AsEnumerable()
        .First(t => t.Name == "ThingamaBob");
 
精彩推荐
图片推荐