Search through Where clause in LINQ, using dynamic properties

前端 未结 4 1188
长情又很酷
长情又很酷 2021-01-12 17:58

I\'m basically trying to construct a query, and I don\'t know why microsoft made this so difficult in Entity Framework and LINQ. I have various parameter STRINGS. So if you

4条回答
  •  情歌与酒
    2021-01-12 18:52

    You'll have to build an expression tree to pass to the Where method. Here's a loose adaptation of some code I have lying about:

    string searchfield, value; // Your inputs
    var param = Expression.Parameter(typeof(User), "user");
    
    return Expression.Lambda>(
        Expression.Call(
            Expression.Property(
                param,
                typeof(User).GetProperty(searchfield)),
            typeof(string).GetMethod("Contains"),
            Expression.Constant(value)),
        param);
    

    That will generate an appropriate expression to use as the parameter to Where.

    EDIT: FYI, the resultant expression will look something like user => user.Foo.Contains(bar).

    EDIT: To sort, something like this (ripped from my DynamicOrderList class):

    private IQueryable OrderQuery(IQueryable query, OrderParameter orderBy)
    {
        string orderMethodName = orderBy.Direction == SortDirection.Ascending ? "OrderBy" : "OrderByDescending";
        Type t = typeof(T);
    
        var param = Expression.Parameter(t, "user");
        var property = t.GetProperty(orderBy.Attribute);
    
        return query.Provider.CreateQuery(
            Expression.Call(
                typeof(Queryable),
                orderMethodName,
                new Type[] { t, typeof(string) },
                query.Expression,
                Expression.Quote(
                    Expression.Lambda(
                        Expression.Property(param, property),
                        param))
            ));
    }
    

提交回复
热议问题