這幾天因業務需要,在使用第三方的ORM查詢數據庫時,已知一些字符串的過濾條件,需要實現query.Where(p=>p.Age.ToString().Contains("2"))這樣的查詢操作,雖然可以用拼接sql語句的方式去實現該功能,但是會破壞程序的擴展性,所以想實現用字符串轉換成Lambda的表達式。具體實現如下:
class Program { static void Main(string[] args) { var exp = GetToString<Person>("Age", 12); Console.WriteLine("Hello World!"); Console.ReadKey(); } public static Expression<Func<T, bool>> GetToString<T>(string propertyName, object propertyValue) { ParameterExpression parameter = Expression.Parameter(typeof(T), "p"); MemberExpression member = Expression.PropertyOrField(parameter, propertyName); //拼接ToString MethodInfo methodToString = member.Type.GetMethod("ToString", new Type[] { }); MethodCallExpression methodCall = Expression.Call(member, methodToString); //拼接Contains MethodInfo methodContains = typeof(string).GetMethod("Contains", new[] { typeof(string) }); ConstantExpression constant = Expression.Constant(propertyValue.ToString(), typeof(string)); MethodCallExpression methodCallContains = Expression.Call(methodCall, methodContains, constant); return Expression.Lambda<Func<T, bool>>(methodCallContains, parameter); } } public class Person { public int Age { get; set; } public string Name { get; set; } }
實現上述代碼時有需要注意幾個地方:
1. 在獲取ToString方法時,我這里調用的方法不需要傳參,但是依然要寫"new Type[]{}",不然會報Ambiguous match found.(找不到明確的匹配項,而且這種寫法也不行:“new []{}”)
2. 在獲取Contains方法時,Contains方法的參數必須是字符串,所以propertyValue要ToString()
Expression很強大,有興趣的可以研究研究!