Linq查询以从多个表中获取计数

时间:2018-12-18 21:24:37

标签: c# sql-server linq

我有一个查询,我需要从2个不同的表中获取计数。这是查询的一种非常简单的形式(我的查询具有更多的联接和条件,但这是我坚持的部分):

select (select count(1) from Table1) as One, (select count(1) from Table2) as Two

以下linq查询有效,但我想通过发送到SQL Server的单个linq查询来完成上述操作。该查询以及我尝试过的其他许多版本,导致向服务器发送了2个查询:

var query1 = from m in this.Table1 select m;
var query2 = from sr in this.Table2 select sr;
var final = new { One = query1.Count(), Two = query2.Count() };

我也尝试过这样做,这还会发送2个查询:

var final = from dummy in new List<int> { 1 }
    join one in query1 on 1 equals 1 into ones
    join two in query2 on 1 equals 1 into twos
    select new { One = ones.Count(), Two = twos.Count()};

1 个答案:

答案 0 :(得分:3)

您需要使其成为一个可以翻译的LINQ查询:

var final = (from m in this.Table1.DefaultIfEmpty()
             select new {
                 One = (from m in this.Table1 select m).Count(),
                 Two = (from sr in this.Table2 select sr).Count()
             }).First();

请注意,将子查询放入IQueryable变量中将导致发送三个单独的查询。

或者,由于Count()没有等效的查询语法,因此在lambda语法中这要紧凑一些:

var final = this.Table1.DefaultIfEmpty().Select(t => new {
                 One = this.Table1.Count(),
                 Two = this.Table2.Count()
            }).First();