【问题标题】:Make LINQ expression case insensitive使 LINQ 表达式不区分大小写
【发布时间】:2021-07-05 06:58:00
【问题描述】:

我有下面的 LINQ 表达式,我需要将 Contains 设为不区分大小写,尝试了不同的方法,但它们都不起作用

ParameterExpression paramExpr = Expression.Parameter(typeof(EmployeeEntity));
var propertyName = Expression.Property(paramExpr, "EmpName");
//for type convertion start
var propertyType = ((PropertyInfo)propertyName.Member).PropertyType;
var converter = TypeDescriptor.GetConverter(propertyType); 
if (!converter.CanConvertFrom(typeof(string))) 
    throw new NotSupportedException();
var propertyValue = converter.ConvertFromInvariantString("john"); 
var constant = Expression.Constant(propertyValue);
var valueExpression = Expression.Convert(constant, propertyType);
//for type convertion ends

MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
var someValue = Expression.Constant(propertyValue, typeof(string));
var finalExpression = Expression.Call(propertyName, method, someValue);

在我的表中,EmpName 是“John”,但我上面的查询将返回零行,所以如何使上面的查询不区分大小写。

【问题讨论】:

  • 您使用的是什么数据库?但无论如何您都可以在您的属性上生成ToLower() 调用。
  • @HimBromBeere 不确定这是否会由 EF 翻译。
  • 您使用哪个版本的 EF?对于 EF 核心,请参阅:stackoverflow.com/questions/43277868/…
  • @GuruStron:我正在使用 MS SQL,我尝试使用 ToLower,但我没有得到确切的语法,你能否提供我上面示例的确切语法

标签: c# entity-framework linq comparison expression


【解决方案1】:

这样可以吗?它应该获取带有 StringComparison 参数的 Contains 方法,并传入忽略大小写的值。

MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string), typeof(StringComparison) });
var someValue = Expression.Constant(propertyValue, typeof(string));
var comparisonValue = Expression.Constant(StringComparison.OrdinalIgnoreCase, typeof(StringComparison));
var finalExpression = Expression.Call(propertyName, method, someValue, comparisonValue);

【讨论】:

  • 我很确定这不会被 EF 翻译。
  • @Steve Harris:感谢您的帮助。这是工作
  • 你可能就在那里@GuruStron。 SQL 中没有一个标志来进行不区分大小写的比较,这将导致查询其中列和值将转换为相同的大小写,或者在应用比较之前从数据库中检索结果。但它会得到所需的结果。
  • @SteveHarris 看来我错了,因为它适用于 OP =)
【解决方案2】:

如果您可以访问您的数据库并且它支持不同的排序规则(例如 MS SQL),那么解决问题的最简单方法是将字段的排序规则更改为不区分大小写的替代方案:

ALTER TABLE [MyTable]
  ALTER COLUMN [MyColumn] NVARCHAR(...) COLLATE Latin1_General_CI_AS 

否则,如 cmets 中所述,您可以为属性和值生成 .ToLower() 调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-22
    • 1970-01-01
    • 1970-01-01
    • 2013-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多