Entity Framework Entity Database Many-to-Many First

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

EF created a UserRole entity and a UserRoles to navigate in the User object and in the Role object, but I would prefer Roles in User and Users in Role . Is it possible for this to be developed by the model designer? How to manually configure many-to-many relationships with a table in the middle?

+1
c # sql database entity-framework many-to-many
Feb 20 '16 at 18:18
source share
1 answer

EF typically creates an intermediate model if the UserRole table contains columns other than foreign keys for the User and Role table.

So, if there were only 2 columns in the UserRoles table, then both FKs for User and Role tables (not even a surrogate key), EF would create the model according to your desire. (without any intermediate model). So this is one way to automatically generate the desired behavior. There are only 2 columns in the table.

But if there are other non-key columns (data) in this table, then what makes EF right. You need an intermediate object.

And if you don’t have any non-key columns, no longer want to change your database and do not need this middle table in your model, you can manually change OnModelCreating to indicate Many-to-Many and hide the intermediate table .

Here are all the steps:

  • Remove the C # staging table class from the model level and its references in the DbContext and User and Role classes.
  • Add the property of the virtual collection both in the User class and the Role for each other.

eg. in the User class,

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

and in the User constructor

 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"); }); 
+5
Feb 20 '16 at 18:35
source share



All Articles