簡體   English   中英

編輯多對多關聯的操作

[英]Edit action for many-to-many association

我在網站上制作新聞標簽。 首先使用實體​​框架代碼。 PostTag關聯表(PostId + TagId)自動生成。 這是我的模特:

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; } 
}

問題在於為我的管理面板實現Post Editor Action。 創建和刪除操作工作正常。 這是我嘗試過的,它會正確更新所有Post字段,但會忽略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");
}
//...

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

感謝gdoron指點方向。

我的消化:

[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
}

我沒有測試過,你能為我們確認一下嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM