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

c# entity-framework expression func linq

Question

Writing a linq to entity extension method that accepts a Func to choose a property Id and compare it against a list of ids is something I'm attempting to do.

Classes

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

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

Extension Approach

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 Technique

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

My issue is that it is attempting to invoke a function that Entity Framework does not permit.

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

1
7
9/4/2014 10:27:48 AM

Accepted Answer

ZZZ_tmp
17
5/23/2017 12:16:51 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow