C# 将用户添加到角色时出现ASP.NET Api错误
我有一个.NETCore2.1应用程序,我正在尝试手动将用户添加到角色中 我没有使用角色管理器,因为我使用的数据库也是由传统的ASP.NET MVC应用程序访问的 我有以下代码来更新用户:C# 将用户添加到角色时出现ASP.NET Api错误,c#,asp.net,asp.net-core,C#,Asp.net,Asp.net Core,我有一个.NETCore2.1应用程序,我正在尝试手动将用户添加到角色中 我没有使用角色管理器,因为我使用的数据库也是由传统的ASP.NET MVC应用程序访问的 我有以下代码来更新用户: public async Task<bool> Update(UserFormViewModel model) { var user = await GetUserById(model.Id); _context.Entry(user).Property(x => x.Id)
public async Task<bool> Update(UserFormViewModel model)
{
var user = await GetUserById(model.Id);
_context.Entry(user).Property(x => x.Id).IsModified = false;
_context.Entry(user).CurrentValues.SetValues(model);
user.AspNetUserRoles.Clear();
await _context.SaveChangesAsync();
foreach (var role in model.Roles)
{
var aspnetuserrole = await _context.AspNetUserRoles.Where(x => x.RoleId == role).Include(x=>x.Role).Include(x=>x.User).FirstOrDefaultAsync();
user.AspNetUserRoles.Add(aspnetuserrole);
}
try
{
var result = await _context.SaveChangesAsync() > 0;
return result;
}
catch (Exception ex)
{
return false;
}
}
这是我的应用程序用户模型:
public class ApplicationUser : IdentityUser
{
[Required]
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<AspNetUserRole> AspNetUserRoles { get; set; }
}
public class AspNetUserRole
{
public string UserId { get; set; }
public ApplicationUser User {get; set;}
public string RoleId { get; set; }
public AspNetRole Role {get; set;}
}
public class AspNetRole
{
[Key]
public string Id { get; set; }
[MaxLength(256)]
[Required]
public string Name {get; set;}
public virtual ICollection<AspNetUserRole> AspNetUserRoles {get; set;}
}
公共类应用程序用户:IdentityUser
{
[必需]
公共字符串名{get;set;}
公共字符串LastName{get;set;}
公共虚拟ICollection AspNetUserRoles{get;set;}
}
公共类AspNetUserRole
{
公共字符串用户标识{get;set;}
公共应用程序用户{get;set;}
公共字符串RoleId{get;set;}
公共AspNetRole角色{get;set;}
}
公共类AspNetRole
{
[关键]
公共字符串Id{get;set;}
[最大长度(256)]
[必需]
公共字符串名称{get;set;}
公共虚拟ICollection AspNetUserRoles{get;set;}
}
试试这个:
foreach (var role in model.Roles)
{
var aspnetuserrole = new AspNetUserRoles()
{
UserId = model.Id,
RoleId = role.Id
};
_context.AspNetUserRoles.Add(aspnetuserrole);
}
foreach (var role in model.Roles)
{
var aspnetuserrole = new AspNetUserRoles()
{
UserId = model.Id,
RoleId = role.Id
};
_context.AspNetUserRoles.Add(aspnetuserrole);
}