我正在尝试编写一个Linq到实体扩展方法,它需要一个Func来选择一个属性Id并将其与一组Ids进行比较。
类
public class A
{
public int AId { get; set; }
}
public class B
{
public int BId { get; set; }
}
Extension Method
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);
我遇到的问题是在 Entity Framework 中无法调用该函数。
如何使用属性选择器(Func)评估查询?
select x where x in (1,2,3)
或在另一个实体关系的情况下执行select x where x in (select y)
。在您的情况下,EF 需要编译类似于select x where x in (select y where F(y) in (F(1),F(2),...))
的内容。虽然手动完成这个过程是可能的,但 EF 目前还不支持这种情况。 - Sten Petrov