LINQ deferred (or immediate?) execution(LINQ 延迟(或立即?)执行)
问题描述
给定以下查询:
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() 方法返回 IQueryable,但第二次返回 FirstOrDefault() 和 ToList()第三个select语句会触发数据库调用?
GetAll() method returns IQueryable, but does FirstOrDefault() and ToList() in second and third select statements will trigger database call ?
任何帮助将不胜感激.
推荐答案
如果您担心生成多个调用,我会考虑使用 实体框架扩展
If you are concerned with generating multiple calls I would consider using EntityFramework Extensions
您可以通过将 .Future() 添加到查询末尾来一起批量查询
You can batch queries together by adding .Future() to the end of a query
例子:
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.
要检查 SQL/批处理,您还可以在查询之前包含以下内容:
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.
这篇关于LINQ 延迟(或立即?)执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:LINQ 延迟(或立即?)执行
基础教程推荐
- 从 C# 控制相机设备 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 将数据集转换为列表 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 如果条件可以为空 2022-01-01
