Many-To-Many Entity Modeling in Entity Framework

In my continued saga to create a new Web site based on ASP.NET 4 Dynamic Data and an Entity Data Model by using the Entity Framework 4, I needed to create or rather model a many-to-many relationships between 3 tables (3 pairs ;-)). While I have no problems doing that with an associated table in a SQL Server database, or any database, for that matter, I hadn’t done that in EF. However, I noticed that the Dynamic Data Web site, I had created, contained field templates for displaying and editing a Many-To-Many relationships. The problem was that while the database did work, I just could not model it using the Designer. Then I noticed that my association table contained three columns, the foreign keys for the two linked tables, but also a separate primary key. I generally create all my tables with an artificial primary key, and I had also done so in this case. Okay, I did a lot of other stuff first, before deciding to try and remove the artificial primary key column (of type uniqueidentifier) and create a composite primary key of the two “foreign key” columns. Then I updated the data model, but no luck. Hmm, okay, I then removed the 3 tables from the model, and subsequently updated the model from the database. In the update wizard, I added back the 3 tables and this time, 3 many-to-may relationships had been created. Great…

However, that wasn’t the best part; Dynamic Data automatically used the many-to-may field controls (ManyToMany.ascx and ManyToMany_Edit.ascx) to model the relationship in the UI. Particularly in edit view this was great, and it has saved me many hours of work. Mind you, a CheckBoxList control is sued, so if you have many rows in the linked table when editing an entity, it can become unwieldy to manage for an end-user.