Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DbSet<T>.Where(where).ToList() - why SQL does not include where clause?

Why is EF 6 querying the database for all records with the following code?

    public virtual List<T> Find(Func<T, bool> where = null)
    {
        _db.Configuration.LazyLoadingEnabled = false;
        if (where == null) throw new NullReferenceException("The 'where' parameter of the Repository.Find() method is null.");    
        return _dbSet.Where(where).ToList();
    }

Produces the following output

SELECT
    [Extent1].[Id] AS [Id],
    [Extent1].[Sequence] AS [Sequence],
    [Extent1].[Description] AS [Description],
    [Extent1].[Instructions] AS [Instructions],
    [Extent1].[WorkCenterOperationId] AS [WorkCenterOperationId],
    [Extent1].[JobId] AS [JobId],
    [Extent1].[JobAssemblyId] AS [JobAssemblyId],
    [Extent1].[RowVersion] AS [RowVersion]
    FROM [dbo].[JobOperations] AS [Extent1]

Two questions:

  1. Why isn't the query executed with the where statement?
  2. How do I get the query to execute with the where statement?
like image 446
Price Jones Avatar asked Feb 14 '23 03:02

Price Jones


1 Answers

You used a Func<T,bool> rather than an Expression<Func<T,bool>> and so you've forced (somewhere) a transition from the database Linq-to-Entities to Linq-to-Objects. So it's processed in memory.


And, as @Marc points out, a simple fix may be:

public virtual List<T> Find(Expression<Func<T, bool>> where = null)
...

But that, in turn, depends on whether the calling code is in a form that can generate either of Func<T,bool> or Expression<Func<T,bool>> (usually, a lambda will be convertible to either form)

like image 187
Damien_The_Unbeliever Avatar answered Feb 15 '23 16:02

Damien_The_Unbeliever