我想添加一个表来定义权限对象,而不是可以应用于许多模型。 为此,我创建了一个Permission类:
public class Permission
{
[Key]
int PermissionID {get; set;}
string User {get; set;}
bool Read {get; set;}
bool Write {get; set;}
}
然后其他对象类可以有一个Permission列表:
public class ObjectModel1
{
[Key]
int idObject1 {get; set;}
... Other properties ...
public virtual ICollection<Permission> Permission {get; set;}
}
public class ObjectModel2
{
[Key]
int idObject2 {get; set;}
... Other properties ...
public virtual ICollection<Permission> Permission {get; set;}
}
如何在不在每个对象的Permission类中定义外键的情况下,在Permission和其他Object类之间获得多对多的关系?
答案 0 :(得分:1)
多对多关系将在两个实体之间有一个外部参照表:
// because Permission has a collection to ObjectModel1 and ObjectModel1 has a collection
// to permission, it is treated as a many to many relationship with an implicit
// xref between the tables. The xref will contain a foreign key to each entity that is
// also a composite primary key
public class Permission
{
[Key]
int PermissionID {get; set;}
string User {get; set;}
bool Read {get; set;}
bool Write {get; set;}
public virtual ICollection<ObjectModel1> ObjectModel1s { get; set; }
public virtual ICollection<ObjectModel2> ObjectModel2s { get; set; }
}
public class ObjectModel1
{
[Key]
int idObject1 {get; set;}
... Other properties ...
public virtual ICollection<Permission> Permission {get; set;}
}
public class ObjectModel2
{
[Key]
int idObject2 {get; set;}
... Other properties ...
public virtual ICollection<Permission> Permission {get; set;}
}
实体框架将创建一个类似于PermissionObjectModel1的表,该表具有带有两个外键的复合主键(一个用于Permission,一个用于ObjectModel1)。它将为具有类似键的ObjectModel2创建另一个表。 Permission本身不存在外键。
如果您不希望获得导航属性,那么我认为您需要使用Fluent API:
public class MyDbContext : DbContext
{
public DbSet<Permission> Permissions { get; set; }
public DbSet<ObjectModel1> ObjectModel1s { get; set; }
public DbSet<ObjectModel2> ObjectModel2s { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ObjectModel1>()
.HasMany(many => many.Permissions)
.WithMany() // dont want navigation property on Permission
.Map(xref => xref.MapLeftKey("ObjectModel1Id")
.MapRightKey("PermissionId")
.ToTable("ObjectModel1PermissionXref"));
modelBuilder.Entity<ObjectModel2>()
.HasMany(many => many.Permissions)
.WithMany() // dont want navigation property on Permission
.Map(xref => xref.MapLeftKey("ObjectModel2Id")
.MapRightKey("PermissionId")
.ToTable("ObjectModel2PermissionXref"));
}
}
类似于上面代码的东西仍然会给你多对多的关系,但导航属性不会在Permission上定义。