我有一些模型(餐馆,商店,产品),我想在单个linq查询中为多个模型选择记录数。
我知道它应该在sql中,但我不知道如何在linq中翻译它:
select
(select count(*) from restaurants) as restaurantsCount,
(select count(*) from shops) as shopsCount,
(select count(*) from products) as productsCount
from
dual
答案 0 :(得分:5)
考虑dual
是一个带有单行的虚拟表:
var result = new
{
RestaurantsCount = context.Restaurants.Count(),
ShopsCount = context.Shops.Count(),
ProductsCount = context.Products.Count()
};
单一查询解决方案:
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()
};