Je suis en train de créer un générateur d'expression dynamique et d'essayer d'implémenter la fonction 'like'. Avant d'écrire le mien, j'ai recherché toute fonction existante et j'en ai trouvé une proche de mon besoin. Après plusieurs expériences, je ne pouvais pas l'amener à courir pour d'autres types de cordes.Entity Framework - requête dynamique
Quand je passe un paramètre de type int
puis-je obtenir cette erreur:
Method 'System.String ToString()' declared on type 'System.String' cannot be called with instance of type 'System.Int32'
Mon code ressemble à ceci:
private static MethodCallExpression GetLowerCasePropertyAccess(MemberExpression propertyAccess)
{
//return Expression.Call(Expression.Call(propertyAccess, "ToString", new Type[0]), typeof(string).GetMethod("ToLower", new Type[0]));
return Expression.Call(Expression.Call(propertyAccess, typeof(string).GetMethod("ToString", System.Type.EmptyTypes)), typeof(string).GetMethod("ToLower", System.Type.EmptyTypes));
}
private static readonly MethodInfo ContainsMethod = typeof(String).GetMethod("Contains", new Type[] { typeof(String) });
public static Expression<Func<T, bool>> Create<T>(string propertyName, ComparisonOperators comparisonOperator, dynamic comparedValue1, dynamic comparedValue2 = null)
{
ParameterExpression parameterExpression = Expression.Parameter(typeof(T), "x");
MemberExpression memberExpression = Expression.MakeMemberAccess(parameterExpression, typeof(T).GetProperty(propertyName));
ConstantExpression constantExpression = Expression.Constant(comparedValue1, comparedValue1.GetType());
Expression expressionBody = null;
switch (comparisonOperator)
{
...
case ComparisonOperators.Contains:
//var indexOf = Expression.Call(memberExpression, "IndexOf", null, Expression.Constant(comparedValue1, typeof(string)), Expression.Constant(StringComparison.InvariantCultureIgnoreCase));
//expressionBody = Expression.GreaterThanOrEqual(indexOf, Expression.Constant(0));
expressionBody = Expression.Call(GetLowerCasePropertyAccess(memberExpression), ContainsMethod, Expression.Constant(comparedValue1.ToLower()));
break;
}
return Expression.Lambda<Func<T, bool>>(expressionBody, new ParameterExpression[] { parameterExpression });
}
J'ai essayé votre solution, mais maintenant j'obtenir une nouvelle erreur: System.NotSupportedException: LINQ to Entities ne reconnaît pas la méthode 'System.String ToString()' méthode, et cette méthode ne peut pas être traduite dans une expression de magasin. – sysboard