简体   繁体   中英

Select records count from multiple tables in a single query

I have some models (restaurants, shops, products), and i want to select records count for multiple models in a single linq query.

I know how it should be in sql, but i don't know how to translate it in linq:

select
    (select count(*) from restaurants) as restaurantsCount,
    (select count(*) from shops) as shopsCount,
    (select count(*) from products) as productsCount
from
    dual

Considering dual is a dummy table with single row:

var result = new 
{ 
    RestaurantsCount = context.Restaurants.Count(),
    ShopsCount = context.Shops.Count(),
    ProductsCount = context.Products.Count()
};

Single query solution:

        var result = from dummyRow in new List<string> { "X" }
                     join product in context.products on 1 equals 1 into pg
                     join shop in context.shops on 1 equals 1 into sg
                     join restaurant in context.restaurants on 1 equals 1 into rg
                     select new
                     {
                         productsCount = pg.Count(),
                         shopsCount = sg.Count(),
                         restaurantsCount = rg.Count()
                     };

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