c# - 实体框架和 ASP.net MVC - 使用多对多关系更新实体模型
问题描述
使用 Asp.Net 身份和实体框架,我正在尝试更新 AspNetUser,并更改其 AspNetRole。
这是我的 UserDto 类:
public class UserDto : BaseDto
{
public string Uuid { get; set; }
public string Email { get; set; }
public string FullName { get; set; }
public string UserName { get; set; }
public List<RoleDto> Roles { get; set; }
public int NumberOfLikes { get; set; }
public int NumberOfComments { get; set; }
public int NumberOfReviews { get; set; }
}
这是我的 RoleDto 类:
public class RoleDto : BaseDto
{
[ScaffoldColumn(false)]
public string Uuid { get; set; }
[Required(ErrorMessage = "This field is required")]
[MinLength(3, ErrorMessage = "Minimum 3 characters")]
[DisplayName("Role Name")]
public string Name { get; set; }
[ScaffoldColumn(false)]
public int NumberOfUsers { get; set; }
}
这是我在 UserController 中的更新方法:
[HttpPost]
public ActionResult Edit(UserViewModel vm)
{
UserDto dto = new UserDto
{
Uuid = vm.Uuid,
Email = vm.Email,
FullName = vm.FullName,
UserName = vm.UserName,
Roles = new List<RoleDto>()
};
dto.Roles.Add(new RoleDto
{
Uuid = vm.RoleId
});
OpUserUpdate update = new OpUserUpdate();
update.userDto = dto;
var result = this.Manager.ExecuteOperation(update);
return RedirectToAction("Index");
}
这是用户更新操作:
public class OpUserUpdate : OpUserBase
{
public override OperationResult Execute(FoodRestaurantEntities entities)
{
var id = this.userDto.Roles[0].Uuid;
if (!string.IsNullOrWhiteSpace(this.userDto.Uuid))
{
var user = entities.AspNetUsers.FirstOrDefault(u => u.Id == this.userDto.Uuid);
var role = entities.AspNetRoles.FirstOrDefault(r => r.Id == id);
if(user != null)
{
// If is set email
if (!string.IsNullOrWhiteSpace(this.userDto.Email))
user.Email = this.userDto.Email;
// If is set full name
if (!string.IsNullOrWhiteSpace(this.userDto.FullName))
user.FullName = this.userDto.FullName;
// If is set full name
if (!string.IsNullOrWhiteSpace(this.userDto.UserName))
user.UserName = this.userDto.UserName;
user.AspNetRoles.Add(role);
entities.SaveChanges();
this.Result.Status = true;
this.Result.Message = "Successfully updated";
}
else
{
this.Result.Status = false;
this.Result.Message = "Not successfull";
}
}
return Result;
}
}
1. OperationManager 类只执行操作 2. 问题是,user.AspNetRoles.Add(role)行只是为用户添加了另一个角色。例如,如果用户具有用户角色,它也会添加管理员角色,而不是将其更改为管理员。我究竟做错了什么?
解决方案
推荐阅读
- sql - 如何以直接、简单的方式获取 MS SQL Server 和数据库空间信息
- python - 同时运行多个使用用户输入和while循环的python脚本
- php - $request 根据我转储它的位置返回不同的值
- amazon-web-services - AWS:Lambda 权限策略可以使用通配符从目标组获取源吗?
- python - Python Jupyter Notebook 无法运行我的代码,不断重新连接
- ruby-on-rails - rails 6外键不能为空
- c# - IFormFile 作为嵌套的 ViewModel 属性
- laravel - 使用 Eloquent 从相关表外键中检索值
- php - 如何使表格上显示的数据随着选择框中选择的值而变化?
- javascript - 如果我的 API 位于不同的“路线”,我该如何访问它?