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"); });
Raja Nadar Feb 20 '16 at 18:35 2016-02-20 18:35
source share