如何使用LINQ到实体框架的表达式中使用函数求? [英] How to use a Func in an expression with Linq to Entity Framework?

查看:185
本文介绍了如何使用LINQ到实体框架的表达式中使用函数求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个LINQ到,需要一个Func键选择属性Id和比较反对ID列表实体扩展方法。

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.

public class A
{
    public int AId { get; set; }
}

public class B
{
    public int BId { get; set; }
}



扩展方法

public static IQueryable<T> WithId<T>(this IQueryable<T> entities,
    Func<T, int> selector, IList<int> ids)
    {
        Expression<Func<T, bool>> expression = x => ids.Contains(selector(x));
        return entities.Where(expression); // error here (when evaluated)
    }



调用方法

var ids = new List<int> { 1, 2, 3 };
DbContext.EntityAs.WithId(e => e.AId, ids);
DbContext.EntityBs.WithId(e => e.BId, ids);



我遇到的问题是,它试图调用这是不是在实体框架允许的功能

The problem I am experiencing is that it is trying to Invoke the function which is not allowed in Entity Framework.

我如何使用属性选择器(Func键),以评估查询?

How can I use a property selector (Func) to evaluate the query?

推荐答案

您将不得不通过一项表达式来; Func键< T,INT>> 而不是一个 Func键< T,INT> ; ,并建立自己完整的表达。这将这样的伎俩:

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

当你试图让你的代码干你的O / RM时,你会经常与表达式树捣鼓。这里是另一个有趣的例子

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.

这篇关于如何使用LINQ到实体框架的表达式中使用函数求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆