I've quite basic question about many-to-many relationships in MVC3 and EF. In my database I have Articles and Tags (many to many), connected by TagArticle table with foreign keys to both tables. In my MVC project I created viewmodel with attributes from both article and tag, I want to use it in one view that allows user create article and choose tags to it. How to make insert operation to that scenario? Thanks for your help.
Asked
Active
Viewed 1,088 times
2 Answers
0
Something like this should "just work":
// get tags by name (tagNames is array of string)
var tags = (from t in db.Tags where tagNames.Contains(t.Name) select t).ToList();
var article = CreateArticleFromPostedForm(...);
var newTags = from tagName in tagNames.Except(tags.Select(t => t.Name)) select new Tag(tagName);
// Tags collection should be initialized properly when creating the article
// NOTE: probably better to add a constructor for Article that accepts a list of Tags
article.Tags.AddRange(tags.Concat(newTags));
db.SaveChanges();

jeroenh
- 26,362
- 10
- 73
- 104
0
If you just need to create new article you can use this approach:
- In your form you must post article and either list of tag ids or tag names assigned to article
- Then you can Add new
Article
to context - If you post ids you must create dummy object for each Tag and attach it to the context
- If you post name you must load tag object for each name from database (you need its id)
- At last you can fill
Tags
to the newArticle
added to the context (it must be same context as used for either attaching or loadingTags
)
So it should be something like:
context.Articles.AddObject(article);
int[] ids = GetIdsFromRequest();
foreach(var tag in ids.Select(id => new Tag { Id = id }))
{
context.Tags.Attach(tag);
article.Tags.Add(tag);
}
context.SaveChanges();
It should work because you know that all relations to tags are new but once you want to modify article and change assigned tags you will need more complicated approach.

Community
- 1
- 1

Ladislav Mrnka
- 360,892
- 59
- 660
- 670