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

Why does EF 6 query 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:

  • Why does the request fail with the where statement?
  • How to get a request to execute with a where statement?
+4
source share
1 answer

You used Func<T,bool>, not Expression<Func<T,bool>>, and therefore you have forcibly (somewhere) switched from the Linq-to-Entities database to Linq-to-Objects. Therefore, it is processed in memory.


And, as @Marc points out, a simple solution could be:

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

, , , , Func<T,bool> Expression<Func<T,bool>> (, lambda )

+8

Source: https://habr.com/ru/post/1537713/


All Articles