user1679941
user1679941

Reputation:

Does a many-many relationship in EF6 require the mapping table to be defined and to have a primary key?

Does an EF6 table used for many to many require a primary key and do I have to create a class for that many to many table? I have seen two ways of creating a many-many table now. The one that's been answered here in this question:

How do I name a many-many table for EF6 and do I need to add special mapping for this?

and the one here in this question:

Entity Framework : many to many relationship , Insert and update

The first answer suggests a table with a primary key while the second answer (with the 6 votes) suggests a very different approach where the many-many table is not defined in EF?

My thoughts right now are that a primary key is not needed. The reason I am thinking this is because when I look at the new tables created by the ASP.NET Identity then the UserRoles table that is many to many does not have a primary key.

Upvotes: 4

Views: 4446

Answers (1)

Colin
Colin

Reputation: 22595

When two entities are related to each other with a many-to-many relationship Entity Framework Code First will create a join table without you having to create an entity class to model the join.

The join table does have a primary key but in this case it is a composite made up from two foreign keys to the tables supporting your entities. In your first link I think the answer is misleading because EF would not generate that sql from that fluent api - but it does tell you how to name the columns and table if you don't like the defaults.

The second example is using database first and modelling the many-to-many in the same standard way. i.e. a primary key that is a composite of two foreign keys.

What you should be aware of is that sometimes you start with a many-to-many relationship, then you realise that the relationship itself has some attributes - and then you have to promote the relationship to an entity in its own right and you will probably add a different primary key

Reference:

Configuring a Many-to-Many Relationship

Upvotes: 4

Related Questions