I found conflicting information on how to update many-to-many relationships in entity framework.
I therefore decided to research the problem properly. I believe I now understand how entity framework works with automatic many-to-many relationships and how to implement my own linking table if I need to.
There are cases when you want to have your own link table, possibly because you want to include some other property in the link table.
One of them has a simple list of blog Posts, each of which has one or many Tags.
The Posts and Tags are linked by a many-to-many table.
After we have saved the changes the Post’s Allocated Tags list will reflect the changes through EF’s relational fixup done on any tracked classes. you add or remove rows from the Post Tag Links table to change the links.
Just like the first example when using MVC I have filled a Multi Select List with all the tags and it returns the ids of the tags that the user has chosen.
So let us carry out the same type of Unit Test (connected) code and the MVC (disconnected) code we did in the first Example.
The two unit tests below now show that we need to manipulate our Post Tag Link table entries, not the navigation properties in the Post.
When working with a web application like MVC an update is done in two stages.
Firstly the current data is sent to the user who updates it.
Secondly when the user presses submit the new data is sent back, but its now disconnected from the database, i.e. This makes for a slightly more complicated case, but still fairly easy to handle. In this case I have filled a Multi Select List with all the tags and it returns the ids of the tags that the user has chosen.
I should also point out I use the same method for create and update, hence the test on line 5 to see if I need to load the current tags collection.
Well, that took longer than I expect to write the blog, but I hope it helps others in really understanding what is going on underneath EF’s many-to-many relationships.