this problem is not about async problems with entityframework itself as discussed here.
In the method CalculateSomething
you can see two LINQ-Calls.
The performance of the first LINQ-Call (initializing result
) is absolutely okay.
However, the performance of the second LINQ-Call (initializing resultWithDate
) Is way slower than the first one.
The first one takes 2 Seconds, The second one takes 15-20 Seconds.
dataBase
is my DbContext
class. Iam using Entity Framework Core.
private async Task<long> CalculateSomething(string numberOne, MyStatus status)
{
var result = await this.dataBase.Something.CountAsync(item => item.NumberOne== numberOne && item.Status == (short)status);
var resultWithDate = await this.dataBase.Something.CountAsync(item => item.NumberOne== numberOne && item.Status == (short)status && !this.IsOlderThan30Days(item.Date));
return result;
}
private bool IsOlderThan30Days(DateTime? itemDate)
{
bool result = true;
if (itemDate.HasValue)
{
if ((DateTime.Now - itemDate.Value).TotalDays <= 30)
{
result = false;
}
}
return result;
}
The problem is not the method call IsOlderThan30Days
, the problem is about CountAsync
. I know this because I had something like this:
private async Task<long> CalculateAmountOfOrders(string numberOne, MyStatus status)
{
var result = this.dataBase.Something.Where(item => item.NumberOne == numberOne && item.Status == (short)status);
var resultWithDate = this.dataBase.Something.Where(item => item.NumberOne == numberOne && item.Status == (short)status && !this.IsOlderThan30Days(item.Date));
var resultCount = await result.CountAsync();
var resultWithDateCount = await resultWithDate.CountAsync();
return resultCount;
}
And the performance loss appeared at the two CountAsync()
calls. CountAsync
on resultWithDateCount
took 15 seconds while CountAsync
on resultCount
only took 2 seconds. initializing result
and resultWithDate
was equally fast.
Am I doing something wrong?
Thank you
using(var db = new Context()) { countOperation(); }
Something else: are you sure your queries are executed through EF? Because I don't think EF can handle theIsOlderThan30Days
through LinqToEntities...initializing result and resultWithDate was equally fast.
That is because in your latter code sample initialisingresult
andresultWithDate
doesn't actually do very much. See learn.microsoft.com/en-us/dotnet/framework/data/adonet/ef/… .IsOlderThan30Days()
) in the seocond query it is executed in memory (since that private method cannot be translated to / executed in SQL). Therefor EF has to load all items before filtering using your where expression, which is most likely the cause for the performance difference. (Can you check the types ofresult
andresultWithDate
? If I'm correct then the first query is anIQueryable
while the other one is anIEnumarable
)IsOlderThan30Days
call which causes client evaluation of the query. In EF6 it would have been a simple exception, but in EF Core it "just works".