2012-01-29 67 views
4

我正在爲網站上的新聞製作標籤。首先使用實體​​框架代碼。 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字段,但會忽略標籤。

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

Thankx到gdoron爲指向的方向。

+0

我對'Entity Framework'不熟悉,但是在'NHibernate'中,你必須將實體附加到會話中,以便跟蹤更改。我認爲這是你的問題。你從頁面獲得的'Post'被分離。我對嗎? – gdoron 2012-01-29 08:10:52

+0

你有沒有檢查你的數據庫,並確保關係是創建? – KMan 2012-01-29 08:11:40

+0

gdoron,我不認爲這是事實。你是什​​麼意思分離? KMan,你們,我檢查了分貝,一切都很好,後期製作的動作也是以同樣的方式完美呈現。 – Wonder 2012-01-29 08:20:08

回答

0

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

我沒有測試過,你能確認我們呢?