Insert to many in many related tables using entity structures in MVC3 and viewmodel

I have a pretty simple question about many-to-many relationships in MVC3 and EF. My database has articles and tags (many for many) related to the TagArticle table with foreign keys for both tables. In my MVC project, I created a viewmodel with attributes from an article and a tag, I want to use it in one view, which allows the user to create an article and select tags for it. How to insert an operation into this script? Thank you for your help.

+3
source share
2 answers

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();
0
source

, :

  • ,
  • Article
  • ,
  • , ( )
  • , Tags Article, ( , Tags)

, - :

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();

, , , , .

0

All Articles