Querying Entity with LINQ using Dyanmic Field Name

前端 未结 3 676
庸人自扰
庸人自扰 2020-12-15 15:08

I have created a dynamic search screen in ASP.NET MVC. I retrieved the field names from the entity through reflection so that I could allow the user to choose which fields

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-15 15:10

    After a lot more trial and error and searching I accidentally found another SO post that covers the same issue:

    InvalidOperationException: No method 'Where' on type 'System.Linq.Queryable' is compatible with the supplied arguments

    Here is my modified code that works:

            IQueryable query = entities.People;
            Type[] exprArgTypes = { query.ElementType };
    
            string propToWhere = "FirstName";            
    
            ParameterExpression p = Expression.Parameter(typeof(People), "p");
            MemberExpression member = Expression.PropertyOrField(p, propToWhere);
            LambdaExpression lambda = Expression.Lambda>(Expression.Equal(member, Expression.Constant("Scott")), p);                            
    
            MethodCallExpression methodCall = Expression.Call(typeof(Queryable), "Where", exprArgTypes, query.Expression, lambda);
    
            IQueryable q = query.Provider.CreateQuery(methodCall);
    

    With some hopefully pretty easy modifications, I should be able to get this to work with any type.

    Thanks again for your answers Ani & John Bowen

提交回复
热议问题