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 延迟(或立即?)执行
基础教程推荐
- 如何激活MC67中的红灯 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- rabbitmq 的 REST API 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01