我花了一天的时间来解决这个问题。有这些实体:
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 进行了尝试,结果相同。