我正在尝试编写一个 linq 到实体扩展方法,该方法需要一个 Func 来选择一个属性 ID 并将其与一个 ID 列表进行比较。
课程
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);
我遇到的问题是它试图调用实体框架中不允许的函数。
如何使用属性选择器 (Func) 来评估查询?