2012-08-24 76 views
0

我花了一天的時間解決了這個問題。有這些entitites:實體代碼第一多對多關係保存

public class UserRole 
{ 
    [Key] 
    public virtual int Id { get; set; } 
    public virtual string Name { get; set; } 
    public virtual ICollection<Privilege> Privileges { get; set; } 
} 

public class Privilege 
{ 
    [Key] 
    public virtual int Id { get; set; } 
    public virtual string Name { get; set; } 
    public virtual ICollection<UserRole> Roles { get; set; } 
} 

而這個配置方面:

modelBuilder.Entity<UserRole>().HasMany<Privilege>(a => a.Privileges).WithMany(a => a.Roles) 
.Map(m => 
    { 
     m.MapLeftKey("RoleId"); 
     m.MapRightKey("PrivilegeId"); 
     m.ToTable("RolesPrivilegesMapping"); 
    }); 

而這個測試代碼:

UserRole role; 
//get role entity from context 
//write privileges count 
using (VaultContext context = new VaultContext(connectionString)) 
{ 
    role = context.UserRoles.Where(a => a.Name == "Users").FirstOrDefault(); 
    Console.WriteLine(role.Privileges.Count.ToString()); //writes 0 
} 

//make offline changes 
//the privilege already exists in database 
role.Privileges.Add(new Privilege() { Id = 1, Name = "Login" }); 

//save changes to database 
using (VaultContext context = new VaultContext(connectionString)) 
{ 
    List<Privilege> privileges = new List<Privilege>(); 
    foreach (Privilege p in role.Privileges) 
    { privileges.Add(p); } 
    foreach (Privilege p in privileges) 
    { context.Privileges.Attach(p); } 
    role.Privileges.Clear(); 
    context.UserRoles.Attach(role); 
    context.Entry(role).State = System.Data.EntityState.Modified; 
    foreach (Privilege p in privileges) 
    { role.Privileges.Add(context.Privileges.Find(p.Id)); } 
    context.SaveChanges(); 
} 

//reload the role entity 
//write privileges count 
using (VaultContext context = new VaultContext(connectionString)) 
{ 
    Console.WriteLine(context.UserRoles.Where(a => a.Name == "Users").FirstOrDefault().Privileges.Count.ToString()); //writes 0 
} 

的用戶角色和登錄權限已在數據庫中。所以我嘗試添加特權登錄到用戶角色。 但是關係不會保存在數據庫中 - RolesPrivilegesMapping表不包含記錄,其id與用戶角色和登錄權限相對應。 如果我乾脆直接添加 - 它的工作原理,但它不是我的目標:

new UserRole() 
{ 
    Name = "Administrators", 
    Privileges = new List<Privilege>() 
    { 
     new Privilege() { Name = "Login" } 
    } 
} 

誰能指點我如何只添加許多一對多的關係,如果在數據庫中存在的所有實體? 我使用EF 5.0。我已經用EF 4.3試過了,結果相同。

回答

0

如果你想要做的就是在數據庫中附加現有條目,你可以做一些簡單的操作嗎?

using(VaultContext context = new VaultContext()) 
     { 
      role = context.UserRoles.FirstOrDefault(a => a.Name == "Users"); 
      Privilege p = context.Privileges.FirstOrDefault(pr => pr.Name == "Login"); 
      role.Privileges.Add(p); 
      context.SaveChanges(); 
     } 
0

謝謝。 這是我的解決方案:(角色離線更改)

UserRole dbRole = context.UserRoles.Find(role.Id); 
dbRole.Privileges.Clear(); 
foreach (Privilege p in role.Privileges) 
{ 
    dbRole.Privileges.Add(context.Privileges.Find(p.Id)); 
} 
context.Entry(dbRole).State = System.Data.EntityState.Modified; 
相關問題