LINQ: Dynamic where with generic property and valu

2019-06-09 03:24发布

问题:

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

回答1:

You can construct the expression manually like this:

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