I have the following query that is causing "The wait operation timed out" when I use sorting by Name
. How can I make it faster? There are 8.5k rows in the Foods
table.
Expression<Func<Food, string>> byName = x => x.FoodTranslations.FirstOrDefault(y => y.Language.Code == CultureInfo.CurrentUICulture.Name).Name;
Expression<Func<Food, string>> byUdsa = x => x.Udsa;
var query = this.DbContext.Foods
.Where(x => category == null || x.FoodTypeId == category)
.Where(x => (string.IsNullOrEmpty(name) || x.FoodTranslations.FirstOrDefault(y=>CultureInfo.CurrentUICulture.Name == y.Language.Code).Name.Contains(name)));
switch (order)
{
case 1:
query = query.OrderBy(byUdsa);
break;
default:
query = query.OrderBy(byName);
break;
}
var result = new JsonFoodIndexResult();
result.Foods = query.Skip(start)
.Take(size)
.Select(x => new JsonFoodIndex
{
Name = x.FoodTranslations.FirstOrDefault(y => y.Language.Code == CultureInfo.CurrentUICulture.Name).Name,
Id = x.Id,
Udsa = x.Udsa,
Category = x.FoodType.FoodTypeTranslations.FirstOrDefault(y => y.Language.Code == CultureInfo.CurrentUICulture.Name).Name
}).ToList();
try
query = query.AsNoTracking().OrderBy(byName);
Entity framework creates Proxy objects to track changes for each record that is ever retrieved & this creation takes a lot of time.Since,while retreiving, we do not need tracking,you can set it as Off as shown above.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.