在单个查询中从多个表中选择记录计数

ale*_*mac 4 c# linq entity-framework entity-framework-6

我有一些模型(餐厅,商店,产品),我想在单个linq查询中选择多个模型的记录数。

我知道它应该在sql中,但是我不知道如何在linq中翻译它:

select
    (select count(*) from restaurants) as restaurantsCount,
    (select count(*) from shops) as shopsCount,
    (select count(*) from products) as productsCount
from
    dual
Run Code Online (Sandbox Code Playgroud)

Ana*_*uza 5

考虑dual是一个单行的表:

var result = new 
{ 
    RestaurantsCount = context.Restaurants.Count(),
    ShopsCount = context.Shops.Count(),
    ProductsCount = context.Products.Count()
};
Run Code Online (Sandbox Code Playgroud)

单一查询解决方案:

        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()
                     };
Run Code Online (Sandbox Code Playgroud)