We have a case in EF:
We have 3 entities, say User, Role and Department. 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
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. Ie its not pure join table (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. When Entity Framework creates a data model, it does not represent the PJT table directly in the data model. 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 :
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.