How to use a Func in an expression with Linq to Entity Framework?

前端 未结 1 592
暗喜
暗喜 2020-12-09 13:22

I am trying to write a linq to entity extension method that takes a Func to select a property Id and compare it against a list of ids.

Classes

相关标签:
1条回答
  • 2020-12-09 13:51

    You'll have to pass an Expression<Func<T, int>> instead of an Func<T, int> and build up the complete expression yourself. This will do the trick:

    public static IQueryable<T> WithId<T>(this IQueryable<T> entities,
        Expression<Func<T, int>> propertySelector, ICollection<int> ids)
    {
        var property =
            (PropertyInfo)((MemberExpression)propertySelector.Body).Member;
    
        ParameterExpression parameter = Expression.Parameter(typeof(T));
    
        var expression = Expression.Lambda<Func<T, bool>>(
            Expression.Call(
                Expression.Constant(ids),
                typeof(ICollection<int>).GetMethod("Contains"), 
                Expression.Property(parameter, property)), 
            parameter);
    
        return entities.Where(expression);
    }
    

    When you try to keep your code DRY when working with your O/RM, you will often have to fiddle with expression trees. Here's another fun example.

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