Change action for many-to-many association

I make tags for news on a website. First use Entity Framework code. PostTag association table (PostId + TagId) is automatically generated. Here are my models:

public class Post { public int Id { get; set; } //... public virtual ICollection<Tag> Tags { get; set; } } public class Tag { public int Id { get; set; } //... public virtual ICollection<Post> Posts { get; set; } } 

The problem is the action of the message editor for my admin panel. Create and delete actions work fine. Here is what I tried, it correctly updates all Post fields, but ignores tags.

 [HttpPost, ValidateInput(false)] public ActionResult Edit(Post post, int[] TagId) { if (ModelState.IsValid) { post.Tags = new List<Tag> { }; if (TagId != null) foreach (int f in TagId) post.Tags.Add(db.Tags.Where(x => x.Id == f).First()); db.Entry(post).State = EntityState.Modified; // Doesnt update tags db.SaveChanges(); return RedirectToAction("Index"); } //... 

Decision

 [HttpPost, ValidateInput(false)] public ActionResult Edit(Post post, int[] TagId) { if (ModelState.IsValid) { Post postAttached = db.Posts.Where(x => x.Id == post.Id).First(); post.Tags = postAttached.Tags; post.Tags.Clear(); if (TagId != null) foreach (int f in TagId) post.Tags.Add(db.Tags.Where(x => x.Id == f).First()); db.Entry(postAttached).CurrentValues.SetValues(post); db.SaveChanges(); return RedirectToAction("Index"); } 

Thanks to gdoron for indicating the direction.

+4
source share
1 answer

My suggestion:

 [HttpPost, ValidateInput(false)] public ActionResult Edit(Post post, int[] tagIds) { if (ModelState.IsValid) { post.Tags = db.Tags.Where(tag => tagIds.Contains(tag.Id)); db.Entry(post).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } // some code here } 

I have not tested, could you confirm this for us?

0
source

Source: https://habr.com/ru/post/1393588/


All Articles