我正在开发基于ASP.net Core 2.0的项目。我创建了ApplicationRole
和ApplicationUser
课程。我在运行项目时编写了一个用于制作角色的代码片段我发现了这个错误:
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查询时,我得到了同样的错误。
列名称无效&#39; ApplicationRoleId&#39;。
SELECT [r].[Id], [r].[Name], [r].[Description], (
SELECT COUNT(*)
FROM [AspNetUsers] AS [a]
WHERE [r].[Id] = [a].[ApplicationRoleId]
) AS [NumberOfUsers]
FROM [AspNetRoles] AS [r]
答案 0 :(得分:1)
不需要Users
课程中的导航属性ApplicationRole
。
AspNetUsers
和AspNetRoles
表之间的关系作为外键存在于单独的表AspNetUserRoles
中。因此,当您要查询给定角色中的用户数时,您需要询问该表AspNetUserRoles
。为了达到这个目的,你可以打电话
_userManager.GetUsersInRoleAsync("roleName").Result.Count;
为此,请执行以下索引操作方法:
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);
}
希望这有帮助。