2013-05-09 185 views
0

我有(2)實體,有如下幾點:更新實體框架實體一對多的關係

[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>(); 
    } 
} 

這將在我的數據庫,用戶,角色和UserRole的三個表。

我利用一個通用的存儲庫,我的新增和更新如下所示:

public virtual void Add(TEntity entity) 
    { 
     _dbSet.Add(entity); 
    } 

    public virtual void Update(TEntity entity) 
    { 
     _dbSet.Attach(entity); 
     _dbContext.Entry(entity).State = EntityState.Modified; 
    } 

如果我想補充與角色新的用戶,我必須做我的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個用戶。

回答

0

你不應該那樣做。如果角色不存在,你會做這樣的事情:

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); 
+0

假設我的用戶已存在並且(4)角色,(2)是新的。所有角色都是預先存在的。 – mattruma 2013-05-09 15:47:53

+0

然後,您只需從角色DbSet中獲取兩個新角色,獲取用戶,通過Roles.Add將角色添加到用戶,然後保存更改。 – 2013-05-09 15:57:35

+0

我猜在哪裏我感到困惑的事實是,我正在使用分離的對象,並且我需要將其掛起以便進行相應的添加。 – mattruma 2013-05-09 16:01:02