简体   繁体   中英

Linq query to get get count from multiple tables

I have a query wherein I need to get the count from 2 different tables. Here is a very simple form of the query (my query has more joins and conditions but this is the part I am stuck on):

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

The following linq queries works but I would like to do the above with a single linq query sent to the SQL Server . This query and many other versions I have tried, result in 2 queries sent to the server:

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() };

I also tried this and this also sends 2 queries:

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()};

You need to make it a single LINQ query that can be translated:

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();

Note that putting the sub-queries into an IQueryable variable will cause three separate queries to be sent.

Alternatively, since Count() doesn't have a query syntax equivalent, this is a little more compact in lambda syntax:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM