I'm trying to build a simple select method for querying Linq-to-SQL table thru a generic static method. I'm stuck at creating the expression dynamically.
Same kind of question here: LINQ : Dynamic select
- T is the class of the database table (Person)
- P is the type of the value. The value and property types should be the same (F.ex String)
- column is the name of property on the given class ("Name")
- value is the where statement value for the field ("Jack")
F.ex Select all persons where name is "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;
}
}