Linq集团由伯爵和伯爵组成

时间:2014-07-16 14:04:25

标签: c# sql linq entity-framework-6

我试图了解group by和count如何与linq合作,但我无法理解如何做我想要的。

我有这张桌子:

ASSET:
Id, Code, Name, ParentId

如果ParentId是根,则为null,如果资产链接到另一个资产,则包含父ID

我想为每个根父母提供Id和子女数

这是我使用的查询:

select father.Id, father.Code, COUNT(children.Id) As NumberOfChildren 
from Asset father 
left join Asset children on(father.Id = children.ParentId) 
where father.ParentId IS NULL 
group by father.Id, father.Code

这是我做的linq查询

var query = from father in this.assetService.GetAll() 
                        join children in this.assetService.GetAll() 
                        on father.Id equals children.ParentId into Children 
                        from children in Children.DefaultIfEmpty() 
                        where father.ParentId.Value == null 
                        group father by new { id = father.Id, code = father.Code } into gf 
                        select new { id = gf.Key.id, count = gf.Count() };

但实体生成该查询:

SELECT 
    1 AS [C1], 
    [GroupBy1].[K1] AS [Id], 
    [GroupBy1].[A1] AS [C2] 
    FROM ( SELECT 
        [Extent1].[Id] AS [K1], 
        [Extent1].[Code] AS [K2], 
        COUNT(1) AS [A1] 
        FROM  [dbo].[Asset] AS [Extent1] 
        LEFT OUTER JOIN [dbo].[Asset] AS [Extent2] ON [Extent1].[Id] = [Extent2].[ParentId] 
        WHERE [Extent1].[ParentId] IS NULL 
        GROUP BY [Extent1].[Id], [Extent1].[Code] 
    )  AS [GroupBy1]

问题来自COUNT(1),我怎么能告诉它应该是COUNT(children.Id)

2 个答案:

答案 0 :(得分:2)

您可以尝试这样的事情:

// Get all the assets in a list.
var assets = this.assetService.GetAll().ToList();

// Get the parents.
var parents = (from asset in assets
               where asset.ParentId == null);

// Remove parents from the original list.
var children = assets.RemoveAll(x => parents.Contains(x));

// Group the children by their parentId
var result = children.GroupBy(x => x.ParentId)
                     .Select(x => new { ParentId = x.Key, Count = x.Count() });

答案 1 :(得分:0)

由于您要处理NULL中的children.Id值,因此在选择最终对象时,您需要一种方法来计算它们。为此,您可以将一个新对象分组,您可以查询该对象以获得正确的计数。这是您正在寻找的修改过的查询对象:

var query = from father in this.assetService.GetAll() 
                        join children in this.assetService.GetAll() 
                        on father.Id equals children.ParentId into Children 
                        from children in Children.DefaultIfEmpty() 
                        where father.ParentId.Value == null 
                        group new { father = father, childExists = (children != null) } by new { id = father.Id, code = father.Code } into gf 
                        select new { id = gf.Key.id, count = gf.Count(o => o.childExists) };

我使用以下C#小提琴来测试它,如果父母没有孩子,它会正确返回0条记录。

https://dotnetfiddle.net/gyqpef

相关问题