C# 使用Concat(实体框架)合并多个IQueryable查询

C# 使用Concat(实体框架)合并多个IQueryable查询,c#,entity-framework,iqueryable,C#,Entity Framework,Iqueryable,我仍然不清楚,例如,我有两个问题: IQueryable<Ad> list1 = db.Ads.Where(x => x.IsModerated == true); IQueryable<Ad> list2 = db.Ads.Where(x => x.TypeId == 1); IQueryable<Ad> list = list1.Concat(list2); foreach(var item in list) { ... } IQue

我仍然不清楚,例如,我有两个问题:

IQueryable<Ad> list1 = db.Ads.Where(x => x.IsModerated == true);
IQueryable<Ad> list2 = db.Ads.Where(x => x.TypeId == 1);
IQueryable<Ad> list = list1.Concat(list2);

foreach(var item in list)
{
   ...
}
IQueryable list1=db.Ads.Where(x=>x.IsModerated==true);
IQueryable list2=db.Ads.Where(x=>x.TypeId==1);
IQueryable list=list1.Concat(list2);
foreach(列表中的变量项)
{
...
}

是一个数据库调用还是两个数据库调用?

它只执行一次。这是一个延迟执行的示例,请阅读此示例以了解更多详细信息

IQueryable<Ad> list1 = db.Ads.Where(x => x.IsModerated == true); -- builds query 1, no db execution
IQueryable<Ad> list2 = db.Ads.Where(x => x.TypeId == 1); -- builds query 2, no db execution
IQueryable<Ad> list = list1.Concat(list2); -- -- builds combine query 'UNION ALL', no db execution

foreach(var item in list) -- query executes here
{
   ...
}
IQueryable list1=db.Ads.Where(x=>x.IsModerated==true);--生成查询1,不执行数据库
IQueryable list2=db.Ads.Where(x=>x.TypeId==1);--生成查询2,不执行数据库
IQueryable list=list1.Concat(list2);--生成组合查询“UNION ALL”,不执行数据库
foreach(列表中的var项)——查询在这里执行
{
...
}

为什么不运行探查器(或等效工具)并查看。在上下文的构造函数中,添加
Database.Log=(s)=>System.Diagnostics.Debug.WriteLine
,它将记录到Visual Studio的输出窗口。然后,您可以看到使用生成的SQLIt执行了多少请求。它可以执行多个查询,具体取决于每个查询的功能。单个
IQueryable
甚至可以执行多个queries@CamiloTerevinto-我很想知道多次执行的情况。据我所知,
.Concat
将两个查询转换为单个
UNION ALL
查询,因此它将执行一次。