我正在研究基于ASP.net Core 2.0的项目。我创建了ApplicationRoleApplicationUser类。在运行项目时,我编写了一段代码来扮演角色,但出现了以下错误:


  System.Data.SqlClient.SqlException:'无效的列名
  “ ApplicationRoleId”。


但是我在ASP.net Core 1.1中使用的相同代码没有任何问题。

我认为这行代码有问题:


  lineNumberOfUsers = r.Users.Count


因为当我评论此代码项目时,它工作正常,但是我需要每个角色的用户数。

控制器:

public class ApplicationRoleController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly RoleManager<ApplicationRole> _roleManager;

    public ApplicationRoleController(UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager)
    {
        _userManager = userManager;
        _roleManager = roleManager;
    }

    public IActionResult Index()
    {
        List<ApplicationRoleViewModel> models = new List<ApplicationRoleViewModel>();
        models = _roleManager.Roles.Select(r => new ApplicationRoleViewModel
        {

            Id = r.Id,
            Name = r.Name,
            Description = r.Description,
            NumberOfUsers =  r.Users.Count
        }).ToList();
        return View(models);
    }
}


模型

public class ApplicationRole : IdentityRole
{
    public string Description { get; set; }
    public virtual ICollection<ApplicationUser> Users { get; } = new List<ApplicationUser>();
}


我已经在SQL Server Profiler中检查了SQL查询。当我在sql server中运行sql查询时,出现了相同的错误。


  无效的列名“ ApplicationRoleId”。


SELECT [r].[Id], [r].[Name], [r].[Description], (
    SELECT COUNT(*)
    FROM [AspNetUsers] AS [a]
    WHERE [r].[Id] = [a].[ApplicationRoleId]
) AS [NumberOfUsers]
FROM [AspNetRoles] AS [r]

最佳答案

不需要Users类中的导航属性ApplicationRole

AspNetUsersAspNetRoles表之间的关系作为外键存在于单独的表AspNetUserRoles中。因此,当您要查询给定角色中的用户数时,需要查询该表AspNetUserRoles。为了做到这一点,你可以打电话

_userManager.GetUsersInRoleAsync("roleName").Result.Count;


为此,请实现您的Index操作方法,如下所示:

public IActionResult Index()
{
  List<ApplicationRoleViewModel> models = new List<ApplicationRoleViewModel>();
  models = _roleManager.Roles.Select(r => new ApplicationRoleViewModel
        {
            Id = r.Id,
            Name = r.Name,
            Description = r.Description
            // notice I am not assigning NumberOfUsers here.See further down...
        }).ToList();

        foreach(var m in models)
        {
          m.NumberOfUsers = _userManager.GetUsersInRoleAsync(m.Name).Result.Count;
        }
        return View(models);
}


希望这可以帮助。

关于c# - System.Data.SqlClient.SqlException:'无效的列名'ApplicationRoleId'。”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49292161/

10-12 06:44