How to set up a many-to-many relationship in Entit

2020-02-14 02:42发布

问题:

I'm an NHibernate developer trying to give Entity Framework a shot in a hobby project. I'm used to specifying mapping data in code using Fluent NHibernate. Pardoning Microsoft's belief that developers shouldn't be allowed to write code, I'm trying to create my mappings using the Entity Framework's visual designer surface (which you get by opening the .edmx file in Visual Studio).

I have no idea how to set up a many-to-many relationship! I have 'updated the model' from the database, but I get two one-to-many relationships with a new entity corresponding to the junction table (which contains only foreign keys and its own primary key).

So far, all attempts at working this out by clicking on the entities and relationships and such have failed. Can anyone give me a pointer?

回答1:

Your junction table must be what MS calls a 'pure join table' - it must contain only the two foreign keys, and no other columns. In your case, that means you must delete the primary key column.



回答2:

When you add the association to the model you choose each of your two tables and choose "many" on both sides of the relationship. When this generates the database script a join table with only the two keys will be created for you.

By the way: If you don't like using Model-first and would rather code research "Code-First" development for the Entity Framework. You can also do Database-First if you prefer that.