I have following simple query in ASP.NET MVC action method.
IEnumerable<Company> query = unitOfWork.CompanyRepository.dbSet
.Include("Adresses.PhoneNumbers")
.Include("Adresses.FaxNumber")
.Include("Emails").Where(q => q.CustomerCompany == true);
This action method is called via ajax get request and sometimes it takes up to 25 secs! for just 40 Companies in database.Each of them has single Address and at most couple of PhoneNumbers and FaxNumbers.(Interestingly it sometimes takes 200-500 msecs, but very rare)
If I change this query to following
IEnumerable<Company> query = unitOfWork.CompanyRepository.dbSet
.Where(q => q.CustomerCompany == true);
It only takes around 200 msecs.
So I am wondering why .Include is so expensive. My application is in production and I am using SQL Azure with Azure Web Sites.
Thanks.
The SQL generated is more complicated, but usually the performance is due to LINQ query compilation overhead. You need to profile to be sure. One possible fix is to use a precompiled query, which will be faster the second and subsequent times. A better fix is probably to use a projection of only the data you need, instead of including 4 entities in the query, which amounts to a
SELECT *on all 4 tables. Another possible fix, if you need all of those full entities, is explicitly loading the details, which means more (but faster!) queries.