Search code examples
c#entity-frameworklinqcomparisonexpression

Make LINQ expression case insensitive


I have bellow LINQ Expression and I need to make Contains as case insensitive, tried different approach but none of them is working

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

In my Table the EmpName is 'John' but my above query will return zero rows, so how to make above query case insensitive.


Solution

  • Will this do it? It should get the Contains method with the StringComparison parameter and pass in the value to ignore case.

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