问题
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