Home > Enterprise >  DbSet.Where in EF fetching all the data
DbSet.Where in EF fetching all the data

Time:09-19

I have using the below code to fetch the matching data based on the where parameter and then removing them but not sure why in the log the query which gets executed shows that it is first fetching all the records from table irrespective of the where filter.

void function(Func<TEntity, bool> where) 
{
    IQueryable objects = DbSet.Where<TEntity>(where).AsQueryable();
    foreach(var obj in objects) 
        DbSet.remove(obj) ;
}

CodePudding user response:

Entity framework uses expression trees to be able to convert lambda expression to sql. You are taking a Func<TEntity, bool>, this causes the DbSet to be converted to a IEnumerable.Where, rather than using a IQueryable.Where, causing all items to be fetched.

You should probably replace the parameter with an Expression<Func<TSource, bool>>. Note that not all expressions can be converted to SQL, and this may result in runtime errors, so you need to be a bit careful how you write expressions.

  • Related