Entity framework 使用多对多关系更新实体框架实体
我有(2)个实体,它们如下:Entity framework 使用多对多关系更新实体框架实体,entity-framework,code-first,Entity Framework,Code First,我有(2)个实体,它们如下: [Table("User")] public class User { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int UserId { get; set; } [Required] [MaxLength(20)] public string Name { get; set; } public ICo
[Table("User")]
public class User
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
[Required]
[MaxLength(20)]
public string Name { get; set; }
public ICollection<Role> Roles { get; set; }
public User()
{
this.Roles = new Collection<Role>();
}
}
[Table("User")]
public class Role
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int RoleId{ get; set; }
[Required]
[MaxLength(20)]
public string Name { get; set; }
public ICollection<User> Users { get; set; }
public Role()
{
this.Users = new Collection<User>();
}
}
如果我想添加一个具有角色的新用户,我必须在UserRepository中执行以下操作,它继承自我的通用存储库
public override void Add(User entity)
{
foreach (var role in entity.Roles)
_dbContext.Roles.Attach(role);
base.Add(entity);
}
这看起来很笨重,但很管用
我的问题是现在我想更新一个用户,比如说添加一个新角色。我想我也可以做类似的事情
public override void Update(User entity)
{
foreach (var role in entity.Roles)
_dbContext.Roles.Attach(role);
base.Update(entity);
}
但这不起作用。。。任何关于我做错了什么的想法都将不胜感激
更新
我的用例是我有一个拥有X个角色的现有用户,我添加了Y个角色,我想用Y个新角色更新用户。你不需要这样做。如果该角色尚不存在,您可以执行以下操作:
var user = new User { Name="Fred" }
user.Roles.Add(new Role { Name="Accounting" });
context.Add(user);
如果要添加现有角色,则需要首先获取该角色
var role = context.Roles.Single(x => x.Name="Accounting");
var user = new User { Name="Fred" }
user.Roles.Add(role);
context.Add(user);
假设我的用户已经存在,并且有(4)个角色,其中(2)个是新角色。所有角色都是预先存在的。然后,您只需从角色数据库集中获取两个新角色,获取用户,通过角色向用户添加角色。添加,然后保存更改。我想我感到困惑的是,我正在处理一个分离的对象,我需要将其连接起来,以便进行适当的添加。
var role = context.Roles.Single(x => x.Name="Accounting");
var user = new User { Name="Fred" }
user.Roles.Add(role);
context.Add(user);