LINQ 延迟(或立即?)执行

LINQ deferred (or immediate?) execution(LINQ 延迟(或立即?)执行)
本文介绍了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 延迟(或立即?)执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)