简体   繁体   English

实体框架数据库首先是多对多的

[英]Entity Framework Database First many-to-many

I've created an Entity Framework model from the database. 我从数据库中创建了一个Entity Framework模型。 I have many-to-many relationship: User - UserRole - Role . 我有多对多的关系: User - UserRole - Role

EF created UserRole entity and UserRoles navigation property in the User entity and in Role entity, but I'd rather have Roles in User and Users in Role . EF创建UserRole实体UserRoles导航属性在User实体和Role的实体,但我宁愿有RolesUserUsersRole Is that possible to be designed through the Model Designer? 这是否可以通过模型设计师设计? How can I configure manually many-to-many relationship with a table in the middle? 如何手动配置中间表的多对多关系?

EF normally creates the intermediate model, if the UserRole table comprises of columns other than foreign keys for User and Role table. 如果UserRole表包含除User和Role表的外键之外的列,则EF通常会创建中间模型。

So if you had just 2 columns in the UserRoles table, both FKs to the User and Role tables (not even a surrogate key), EF would create the Model as you wanted. 因此,如果UserRoles表中只有2列,则用户和角色表的FK(甚至不是代理键),EF都可以根据需要创建模型。 (without any intermediate model) So that is one way to go, for automatic generation of the desired behavior. (没有任何中间模型)因此,这是一种方法,可以自动生成所需的行为。 Have just 2 columns in the table. 表中只有2列。

But if you have other non-key columns (data) in this table, then what EF is doing is correct. 但是如果你在这个表中有其他非键列(数据),那么EF正在做的是正确的。 You need the intermediate entity. 你需要中间实体。

And in the case where you don't have any non-key columns, don't want to modify your DB anymore and don't need this middle table in your model, you could manually modify the OnModelCreating, to specify the Many-to-Many and hide the intermediate table. 如果您没有任何非键列,不想再修改数据库,并且不需要在模型中使用此中间表,则可以手动修改OnModelCreating,以指定Many-to - 很多并隐藏中间表。

Here are all the steps: 以下是所有步骤:

  1. Remove the intermediate table definition C# class from the model layer, and its references in DbContext and User and Role classes. 从模型层中删除中间表定义C#类,并在DbContext和User和Role类中删除它们。
  2. Add a virtual Collection property in both User and Role class, for each other. 在User和Role类中为彼此添加虚拟Collection属性。

eg in the User class, 例如在User类中,

public virtual ICollection<Role> Roles { get; set; }

and in the User constructor 并在User构造函数中

this.Roles = new HashSet<Role>();

// on the OnModelCreating method, add this snippet
modelBuilder.Entity<User>().HasMany<Role>(u => u.Roles)
                          .WithMany(r => r.Users)
                          .Map(ru => 
                                   {  
                                     ru.MapLeftKey("UserId");        
                                     ru.MapRightKey("RoleId"); 
                                     ru.ToTable("UserRole"); 
                                   });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM