Question

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?
Était-ce utile?

La solution

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)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top