如何创建一个LINQ语句来计算连接表?

时间:2014-11-23 08:48:48

标签: c# linq

我的Entity Framwork Identity中有两个类:

public partial class AspNetRole
{        
public AspNetRole()
    {
        this.AspNetUsers = new List<AspNetUser>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<AspNetUser> AspNetUsers { get; set; }
}

public partial class AspNetUser
{
    public AspNetUser()
    {
        this.AspNetRoles = new List<AspNetRole>();
    }
    public int Id { get; set; }
    public string UserName { get; set; }
    public virtual ICollection<AspNetRole> AspNetRoles { get; set; }

}

我正在使用此LINQ查询来获取roleId和拥有的用户 那个角色:

var user1 = await db.AspNetRoles
            .Include(u => u.AspNetUsers)
            .Select(u => new RoleGetDTO
            {
                RoleId = u.Id,
                Name = u.Name,
                Users = u.AspNetUsers.Select(y => new RoleGetDTO.User
                {
                    UserId = y.Id,
                    Name = y.UserName
                }).ToList()
            })
            .ToListAsync();

有人能帮助我吗?现在,而不是显示我想要的用户集合 获取角色中的用户数。

现在是我的RoleDTO:

    public class RoleGetDTO
    {
        public int RoleId { get; set; }
        public string Name { get; set; }
        public virtual ICollection<User> Users { get; set; }

        public class User
        {
            public int UserId { get; set; }
            public string Name { get; set; }
        }
    }

我想将其更改为:

    public class RoleGetDTO
    {
        public int RoleId { get; set; }
        public string Name { get; set; }
        public int UserCount { get; set; }
    }

我希望我的问题有道理,希望有人能告诉我如何更改LINQ,以便现在为每个RoleId填充UserCount整数。

2 个答案:

答案 0 :(得分:1)

只需调用Count方法:

var user1 = await db.AspNetRoles
            .Include(u => u.AspNetUsers)
            .Select(u => new RoleGetDTO
            {
                RoleId = u.Id,
                Name = u.Name,
                UserCount = u.AspNetUsers.Count()
            })
            .ToListAsync();

答案 1 :(得分:1)

试试这个:

var user1 = await db.AspNetRoles
        .Include(u => u.AspNetUsers)
        .Select(u => new RoleGetDTO
        {
            RoleId = u.Id,
            Name = u.Name,
            UsersCount = u.AspNetUsers.Count()
        })
        .ToListAsync();