简体   繁体   中英

Edit action for many-to-many association

I'm making tags for news on web site. Using Entity Framework Code First. 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 in implementing Post Editor Action for my administration panel. Create and Delete actions work fine. Here is what I've tried, it updates all the Post fields properly, 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");
}
//...

Solution

[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");
    }

Thankx to gdoron for pointing the direction.

My sugestion:

[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 do not tested, could you confirm it for us?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM