LINQ 计数相同 table

LINQ count in same table

我的代码优先 entity framework 上下文中有这个 class 如下 -

class User
{
   int UserId;
   string Name;;
   int ParentId;
}

数据库table:

  UserId    Name  ParentId
   1         abc     0
   3         pqr     1
   4         xyz     1

我想 select 从上面的数据中得到 -

 UserId     Name   ChildQuantity
   1         abc        2
   3         pqr        0
   4         xyz        0

我可以使用 LINQ 或 Lambda 来完成吗?

是这样的吗?

var ans = from p in src select new { p.UserID, p.Name, ChildQuantity = src.Where(c => c.ParentId == p.UserID).Count() };

您可以加​​入 table 自己(您需要在这里加入一个群组):

from u in db.Users
join c in db.Users on u.UserId equals c.ParentId into children
select new
{
    u.UserId,
    u.Name,
    ChildQuantity = children.Count()
};

或者您可以为用户 class 中的 children 集合设置一个导航 属性。使用此导航 属性 查询将如下所示:

   from u in db.Users
   select new {
      u.UserId,
      u.Name,
      ChildQuantity = u.Children.Count()
   };

我相信它更干净了。您需要做的就是为 children 添加一个关联 属性:

public class User
{
    public int UserId { get; set; }
    public string Name { get; set; }        
    public int? ParentId { get; set; } // Note: this property is not required
    public IList<User> Children { get; set; }
}

并提供映射:

modelBuilder.Entity<User>().HasMany(u => u.Children)
    .WithOptional().HasForeignKey(u => u.ParentId).WillCascadeOnDelete(false);

生成的查询将如下所示:

SELECT
    [Extent1].[UserId] AS [UserId],
    [Extent1].[Name] AS [Name],
    (SELECT
        COUNT(1) AS [A1]
        FROM [dbo].[Users] AS [Extent2]
        WHERE [Extent1].[UserId] = [Extent2].[ParentId]) AS [C1]
    FROM [dbo].[Users] AS [Extent1]