Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在单个查询中从多个表中选择记录计数_C#_Linq_Entity Framework_Entity Framework 6 - Fatal编程技术网

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

C# 在单个查询中从多个表中选择记录计数,c#,linq,entity-framework,entity-framework-6,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

我有一些模型(餐馆、商店、产品),我想在一个linq查询中为多个模型选择记录计数

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

select
    (select count(*) from restaurants) as restaurantsCount,
    (select count(*) from shops) as shopsCount,
    (select count(*) from products) as productsCount
from
    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()
                     };
var result=来自新列表中的dummyRow{“X”}
连接上下文中的产品。1上的产品等于1进入pg
在上下文中加入shop.shops on 1等于1进入sg
加入上下文中的餐厅。1上的餐厅等于1进入rg
选择新的
{
productsCount=pg.Count(),
shopsCount=sg.Count(),
RestaurantCount=rg.Count()
};

您可以使用LinQ
Union
语句来联合子查询。在您的情况下,将执行三个查询,而不是一个查询。每个计数都有一个()。@Alexander您的
SQL
中确实有相同的值。如果唯一的问题是单次查询实际上不会改变获取数据的方式,那么我将更新答案。@Anatoligabuza在单次查询中执行此操作是否不会提高性能?在我的情况下,第二种解决方案(单次查询)要慢得多-首先加载所有数据,然后计数。。而不是要求DB在单独的查询中只给出计数(简单操作)