实体框架数据库首先是多对多 [英] Entity Framework Database First many-to-many

查看:142
本文介绍了实体框架数据库首先是多对多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经从数据库创建了一个Entity Framework模型。我有多对多的关系: User - UserRole - 角色

I've created an Entity Framework model from the database. I have many-to-many relationship: User - UserRole - Role.

EF创建 UserRole 实体和 UserRoles 导航属性用户实体和角色实体,但我宁愿有角色 中的用户用户是否可以通过模型设计器进行设计?

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. 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通常创建中间模型,如果UserRole表包含除用户和角色表的外键之外的列。

EF normally creates the intermediate model, if the UserRole table comprises of columns other than foreign keys for User and Role table.

因此,如果您在UserRoles表中只有两列,则两个FK角色表(甚至不是代理键),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. (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.

但是如果在这个表中有其他非键列(数据),那么EF正在做的是正确的。您需要中间实体。

But if you have other non-key columns (data) in this table, then what EF is doing is correct. You need the intermediate entity.

在没有任何非键列的情况下,不要再修改数据库,不要在你的模型中需要这个中间表,你可以手动修改OnModelCreating,指定多对多并隐藏中间表。

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.

以下是所有步骤:


  1. 从模型层中移除中间表定义C#类,并在DbContext和User和Role类中引用它。

  2. 在User和Role类中为彼此添加虚拟集合属性。

例如在User类中,

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

和用户构造函数

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"); 
                                   });

这篇关于实体框架数据库首先是多对多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆