Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 584
alexmac Avatar asked Jan 17 '14 09:01

alexmac


1 Answers

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()
                     };
like image 177
Anatolii Gabuza Avatar answered Oct 11 '22 13:10

Anatolii Gabuza