我正在尝试构建一个简单的select方法,通过一个通用的静态方法查询Linq-to-SQL表。我坚持动态创建表达式。
这里有同样的问题:LINQ : Dynamic select
F.ex选择姓名为“Jack”的所有人= Person.Name =“Jack”
public static List<T> selectBy<T,P>(String column, P value) where T : class {
try {
// First resolve the used table according to given type
Table<T> table = database.GetTable<T>();
// Get the property according to given column
PropertyInfo property = typeof(T).GetTypeInfo().GetDeclaredProperty(column);
//Func<Data,Data> expressionHere
// Select all items that match the given expression
List<T> objectList = table.Where(expressionHere).ToList<T>();
// Return the filled list of found objects
return objectList;
} catch (Exception ex) {
Debug.WriteLine("selectBy", ex.Message.ToString());
return null;
}
}
答案 0 :(得分:1)
您可以像这样手动构建表达式:
// First resolve the used table according to given type
Table<T> table = database.GetTable<T>();
// Get the property according to given column
PropertyInfo property = typeof(T).GetTypeInfo().GetDeclaredProperty(column);
//Func<Data,Data> expressionHere
ParameterExpression lambdaArg = Expression.Parameter(typeof(T));
Expression propertyAccess = Expression.MakeMemberAccess(lambdaArg, property);
Expression propertyEquals = Expression.Equal(propertyAccess, Expression.Constant(value, typeof(P)));
Expression<Func<T, bool>> expressionHere = Expression.Lambda<Func<T, bool>>(propertyEquals, lambdaArg);
// Select all items that match the given expression
List<T> objectList = table.Where(expressionHere).ToList<T>();
// Return the filled list of found objects
return objectList;