0

I have the following fluent configuration for a simple many to many relationship between user and roles. I need navigation properties both ways, and therefore have a collection of Users in Role, and vice versa.

When I insert a new entity into User, EF attempts to insert a Role_Id column, when I have mapped it using the following. The column is clearly RoleId, not Role_Id, moreover it's in a many to many table. There cannot be a Role_Id on the User.

I imagine by having a collection on both sides EF is getting confused somehow.

modelBuilder.Entity<User>().HasMany(_ => _.Roles).WithMany()
                        .Map(_ => 
                        {
                            _.MapLeftKey("UserId");
                            _.MapRightKey("RoleId");
                            _.ToTable("UserRole", "dbo");
                        });         

When I attempt to create the relationship the other way, by putting the following configuration after the above one, I get an exception stating that the relationship is already defined.

modelBuilder.Entity<Role>().HasMany(_ => _.Users).WithMany()
                    .Map(_ =>
                    {
                        _.MapLeftKey("RoleId");
                        _.MapRightKey("UserId");
                        _.ToTable("UserRole", "dbo");
                    });         
Jim
  • 14,952
  • 15
  • 80
  • 167

1 Answers1

0

I figured this out, simple really, because the relationship is two ways I have to specify the other leg.

The way I had it works when the navigation is one way. This works when the navigation is two ways.

modelBuilder.Entity<Role>().HasMany(_ => _.Users).WithMany(_ => _.Roles)
                    .Map(_ =>
                    {
                        _.MapLeftKey("RoleId");
                        _.MapRightKey("UserId");
                        _.ToTable("UserRole", "dbo");
                    });      
Jim
  • 14,952
  • 15
  • 80
  • 167