Help with Linq and Generics. Using GetValue inside a Query

前端 未结 2 1340
小蘑菇
小蘑菇 2020-12-03 16:34

I\'m triying to make a function that add a \'where\' clause to a query based in a property and a value. This is a very simplefied version of my function.

Pri         


        
相关标签:
2条回答
  • 2020-12-03 16:58

    You need to convert the code to an expression tree.

    using System;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Reflection;
    
    namespace WindowsFormsApplication1
    {
        static class Program
        {
            [STAThread]
            static void Main()
            {
                using (var context = new NorthwindEntities())
                {
                    IQueryable<Customer> query = context.Customers;
                    query = Simplified<Customer>(query, "CustomerID", "ALFKI");
                    var list = query.ToList();
                }
            }
    
            static IQueryable<T> Simplified<T>(IQueryable<T> query, string propertyName, string propertyValue)
            {
                PropertyInfo propertyInfo = typeof(T).GetProperty(propertyName);
                return Simplified<T>(query, propertyInfo, propertyValue);
            }
    
            static IQueryable<T> Simplified<T>(IQueryable<T> query, PropertyInfo propertyInfo, string propertyValue)
            {
                ParameterExpression e = Expression.Parameter(typeof(T), "e");
                MemberExpression m = Expression.MakeMemberAccess(e, propertyInfo);
                ConstantExpression c = Expression.Constant(propertyValue, propertyValue.GetType());
                BinaryExpression b = Expression.Equal(m, c);
    
                Expression<Func<T, bool>> lambda = Expression.Lambda<Func<T, bool>>(b, e);
                return query.Where(lambda);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-03 16:59

    Have you tried pulling out the DirectCast and reflecting on the lambda parameter instead? Something like this:

    query.Where(Function(c) _
        c.GetType().GetProperty(p, GetType("Int64")).GetValue(c, Nothing) = PValue)
    

    I'm not certain you can even do this sort of thing in a lambda, but it's worth a shot.

    0 讨论(0)
提交回复
热议问题