LINQ deferred (or immediate?) execution

♀尐吖头ヾ 提交于 2021-02-16 14:20:31

问题


Given the following query:

List<GetMultipleLookupListsOutput> data = await _masterListTranslationsRepository
.GetAll()    //<- it returns IQueriable
.GroupBy(q => q.ListLabelID)
.Select(q => q
   .OrderByDescending(w=>w.ISOLanguageCode == isoLanguageCode)
   .ThenByDescending(w=>w.ISOLanguageCode == "en-US"))
.Select(q => q.FirstOrDefault())   // DB call ?
.GroupBy(q=>q.ListLabels.Lists.ListName)
.Select(q => new GetMultipleLookupListsOutput
{
    ListName = q.Key,
    LookupLists = q
       .OrderByDescending(w => w.ISOLanguageCode == isoLanguageCode)
       .ThenByDescending(w => w.ISOLanguageCode == "en-US")
       .Select(w => new RegionalFeatureDto
       {
          Id = w.Id,
          Label = w.BaseValue
       })
       .ToList()   // DB call ?
})
.ToListAsync();

How many database calls will it generate ?

GetAll() method returns IQueryable, but does FirstOrDefault() and ToList() in second and third select statements will trigger database call ?

Any help would be greatly appreciated.


回答1:


If you are concerned with generating multiple calls I would consider using EntityFramework Extensions

You can batch queries together by adding .Future() to the end of a query

Example:

db.BlogPosts.Where(x => x.Category.Any(y => y.Name.Contains("EntityFramework"))).Future();

So to answer your question you could combine these into one call to the database.

To check the SQL/batching you can also include this before your query:

db.Database.Log = s => System.Diagnostics.Debug.WriteLine($"SQL: {s}");

and the log will be displayed in your output window.



来源:https://stackoverflow.com/questions/38079586/linq-deferred-or-immediate-execution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!