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
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)
}
Calling Method
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.
How can I use a property selector (Func) to evaluate the query?
select x where x in (1,2,3)
in the case of enumerable orselect x where x in (select y)
in the case of another entity relationship. In your case EF would need to compile something likeselect x where x in (select y where F(y) in (F(1),F(2),...))
. While it's possible to do this manually EF just doesn't support the case yet – Desiredesirea