实体框架FirstOrDefault中的字符串比较异常 [英] String Comparison exception within Entity Framework FirstOrDefault

查看:56
本文介绍了实体框架FirstOrDefault中的字符串比较异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用实体框架查询表.代码的第一部分是我编写的,第二部分是ReSharper建议我也对其进行重构的内容.如果键不存在,第一个将正常返回null,但是第二个将引发异常.

I'm querying a table using Entity Framework. The first bit of code was what I wrote, the second bit was what ReSharper suggested I refactor it too. The first one gracefully returns null as it should if the key doesn't exist, but the second throws an exception.

尝试使用表中的0-1条记录(所有列均标记为NOT NULL)

This was attempted with 0-1 records in the table (all of the columns are marked as NOT NULL)

有效的代码:

context.brandlink.FirstOrDefault(x => x.ManufacturerKey.ToLower() == manufacturerKey.ToLower());

和无效的代码:

context.brandlink.FirstOrDefault(x => String.Equals(x.ManufacturerKey, manufacturerKey, StringComparison.InvariantCultureIgnoreCase));

引发异常:

为调用方法'Boolean提供的参数数量不正确等于(System.String,System.String,System.StringComparison)'

Incorrect number of arguments supplied for call to method 'Boolean Equals(System.String, System.String, System.StringComparison)'

所以我的问题是:两个表达式之间有什么区别?

So my question is: what is the difference between the two expressions?

推荐答案

所以我的问题是:两个表达式之间有什么区别?

So my question is: what is the difference between the two expressions?

区别在于后者正在使用CLR 规范函数映射的CLR方法,同时支持前者中使用的所有方法( string.ToLower 和字符串相等运算符)

The diffence is that the later is using the CLR String.Equals Method (String, String, StringComparison) which is not supported by EF according to CLR Method to Canonical Function Mapping while all the methods used in the former (string.ToLower and string equality operator) are supported.

通常,您无法控制代码中EF查询的字符串比较,因为它们是由数据库控制的.

In general you cannot control the string comparisons for EF queries from code because they are controlled by the database.

这篇关于实体框架FirstOrDefault中的字符串比较异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆