简体   繁体   English

EF中的多对多映射

[英]Many to Many Mapping in EF

We have a case in EF: 我们在EF中有一个案例:

We have 3 entities, say User, Role and Department. 我们有3个实体,例如用户,角色和部门。 A User can play one or more roles in each department and that can be active or inactive. 用户可以在每个部门中扮演一个或多个角色,并且可以是活动的或不活动的。 So, the columns in Mapping table are as follows: 因此,“映射”表中的列如下:

UserId, RoleId, DeptId, IsActive UserId,RoleId,DeptId,IsActive

We are currently managing the mapping by creating another entity for mapping table, which forces to perform delete operations manually if I have to delete a relationship. 当前,我们正在通过创建用于映射表的另一个实体来管理映射,如果必须删除关系,该实体将强制手动执行删除操作。

IS there a way this can be achieved without any entity for mapping table. 有没有一种方法可以在没有任何实体映射表的情况下实现这一目标。

Thanks in advance. 提前致谢。

No, you cannot avoid junction entity creation, because it does not contain only foreign keys - you have IsActive column. 不,您不能避免创建结实体,因为它不只包含外键-您具有IsActive列。 Ie its not pure join table (PJT): 即它不是联接 (PJT):

Entity Framework (Entity Framework) creates many-to-many relationships in the data model when the join table that represents a many-to-many relationship contains only keys. 当表示多对多关系的联接表仅包含键时,实体框架(Entity Framework)在数据模型中创建多对多关系。 When Entity Framework creates a data model, it does not represent the PJT table directly in the data model. 实体框架创建数据模型时,并不直接在数据模型中表示PJT表。 Instead, Entity Framework creates a direct-navigation relationship between the related tables, known as a many-to-many association. 相反,实体框架在相关表之间创建直接导航关系,称为多对多关联。

But in your case even removing additional column will not help, because Entity Framework need to have collection of joined entities on each side (ie direct-navigation relationship). 但是,在您的情况下,即使删除其他列也无济于事,因为实体框架需要在每一侧都具有已连接实体的集合(即直接导航关系)。 But thus you are joining each entity with other two, you cannot have this collection without providing additional junction entity. 但是因此,您要将每个实体与其他两个实体连接在一起,因此,如果不提供其他联结实体,就无法拥有此集合。

UPDATE: You can configure cascade deletion for this relationship with WillCascadeOnDelete : 更新:您可以使用WillCascadeOnDelete为此关系配置级联删除:

modelBuilder.Entity<User>()
    .HasMany(u => u.RoleDepartments)
    .WithRequired(urd => urd.User)
    .WillCascadeOnDelete();

modelBuilder.Entity<Role>()
    .HasMany(r => r.UserDepartments)
    .WithRequired(urd => urd.Role)
    .WillCascadeOnDelete();

modelBuilder.Entity<Department>()
    .HasMany(d => d.UserRoles)
    .WithRequired(urd => urd.Department)
    .WillCascadeOnDelete();

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

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