我花了一天时间解决这个问题。有这些权利:
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
}
“用户”角色和“登录”权限已在数据库中。所以我尝试添加Login to Users角色权限。 但关系不会保存在数据库中 - RolesPrivilegesMapping表不包含id与Users角色和Login权限对应的记录。 如果我直接添加 - 它可以工作,但它不是我的目标:
new UserRole()
{
Name = "Administrators",
Privileges = new List<Privilege>()
{
new Privilege() { Name = "Login" }
}
}
如果数据库中存在所有实体,有人可以建议我如何只添加多对多关系吗? 我正在使用EF 5.0。我用EF 4.3尝试了相同的结果。
答案 0 :(得分: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();
}
答案 1 :(得分: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;