Entity Framework Core count does not have optimal performance

前端 未结 9 1561
故里飘歌
故里飘歌 2020-12-20 12:19

I need to get the amount of records with a certain filter.

Theoretically this instruction:

_dbContext.People.Count (w => w.Type == 1);
         


        
9条回答
  •  渐次进展
    2020-12-20 12:29

    I am using EFCore 1.1 here.

    This can occur if EFCore cannot translate the entire Where clause to SQL. This can be something as simple as DateTime.Now that might not even think about.

    The following statement results in a SQL query that will surprisingly run a SELECT * and then C# .Count() once it has loaded the entire table!

       int sentCount = ctx.ScheduledEmail.Where(x => x.template == template &&
                       x.SendConfirmedDate > DateTime.Now.AddDays(-7)).Count();
    

    But this query will run an SQL SELECT COUNT(*) as you would expect / hope for:

       DateTime earliestDate = DateTime.Now.AddDays(-7);
       int sentCount = ctx.ScheduledEmail.Where(x => x.template == template 
                       && x.SendConfirmedDate > earliestDate).Count();
    

    Crazy but true. Fortunately this also works:

       DateTime now = DateTime.Now;
       int sentCount = ctx.ScheduledEmail.Where(x => x.template == template &&
                       x.SendConfirmedDate > now.AddDays(-7)).Count();
    

提交回复
热议问题