Entity Framework FirstOrDefault 内的字符串比较异常
String Comparison exception within Entity Framework FirstOrDefault
我正在使用 Entity Framework 查询 table。第一段代码是我写的,第二段是 ReSharper 建议我重构的。如果键不存在,第一个优雅地 returns null,但第二个抛出异常。
尝试使用 table 中的 0-1 条记录(所有列都标记为 NOT NULL)
有效代码:
context.brandlink.FirstOrDefault(x => x.ManufacturerKey.ToLower() == manufacturerKey.ToLower());
和不起作用的代码:
context.brandlink.FirstOrDefault(x => String.Equals(x.ManufacturerKey, manufacturerKey, StringComparison.InvariantCultureIgnoreCase));
抛出异常:
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?
不同之处在于后者使用 CLR String.Equals Method (String, String, StringComparison) which is not supported by EF according to CLR Method to Canonical Function Mapping,而前者使用的所有方法(string.ToLower
和字符串相等运算符)均受支持。
通常您无法从代码控制 EF 查询的字符串比较,因为它们由数据库控制。
我正在使用 Entity Framework 查询 table。第一段代码是我写的,第二段是 ReSharper 建议我重构的。如果键不存在,第一个优雅地 returns null,但第二个抛出异常。
尝试使用 table 中的 0-1 条记录(所有列都标记为 NOT NULL)
有效代码:
context.brandlink.FirstOrDefault(x => x.ManufacturerKey.ToLower() == manufacturerKey.ToLower());
和不起作用的代码:
context.brandlink.FirstOrDefault(x => String.Equals(x.ManufacturerKey, manufacturerKey, StringComparison.InvariantCultureIgnoreCase));
抛出异常:
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?
不同之处在于后者使用 CLR String.Equals Method (String, String, StringComparison) which is not supported by EF according to CLR Method to Canonical Function Mapping,而前者使用的所有方法(string.ToLower
和字符串相等运算符)均受支持。
通常您无法从代码控制 EF 查询的字符串比较,因为它们由数据库控制。