Matt Morgan Matt Morgan - 3 months ago 13
C# Question

Generic EF6 Repository Method Doesn't Generate Correct SQL

I have this method in my repository exposing EF6 DbContext.

public IList<T> GetEntities<T>(Func<T, bool> predicate) where T : class
{
return db.Set<T>().Where(predicate).ToList<T>();
}


When I watch this method execute in SQL Profiler, the predicate is executed in memory. The SQL statement contains no where clause.

Any ideas?

Answer

Your predicate should be an Expression so that Entity Framework can actually use it to generate SQL instead of just executing it. If you pass in a Func you are actually calling the Enumerable.Where method instead of Queryable.Where:

public IList<T> GetEntities<T>(Expression<Func<T, bool>> predicate) where T : class
{
    return db.Set<T>().Where(predicate).ToList<T>();
}