I have the following entities:
public class User
{
public virtual ICollection<Role> Roles { get; set; }
}
public class Role
{
public virtual ICollection<User> Users { get; set; }
}
And the following code in MyContext.OnModelCreating:
mb.Conventions.Remove<OneToManyCascadeDeleteConvention>();
mb.Entity<T>().ToTable("Users", "myschema");
mb.Entity<T>().ToTable("Roles", "myschema");
mb.Entity<User>().HasMany(x => x.Roles).WithMany().Map(a => a.ToTable("UsersRoles", "myschema"));
mb.Entity<Role>().HasMany(x => x.Permissions).WithMany().Map(a => a.ToTable("RolesPermissions", "myschema"));
All other conventions are the default ones. During database initialization, the Users table has a foreign key column Role_Id. This does not make sense. The Users, Roles, and UsersRoles tables are otherwise correct.
While using EF, the User.Role_Id is always NULL and transactions succeed, and UsersRoles is updated as expected. If I delete the column, EF fails complaining about it.
Why is EF doing this and how can I fix it — preferably removing the unnecessary column?
This mapping is wrong:
It must be:
Your first mapping tells EF that you have a many-to-many relationship without exposed navigation property in
Role. Therefore EF assumes thatRole.Usersbelongs to another – by default one-to-many – relationship betweenUserandRolewhich has an end inUser, also not being exposed in the model. The FK column you see belongs to this second association.