简体   繁体   中英

LINQ deferred (or immediate?) execution

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.

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM