2012-06-18 57 views
0

我知道這是一個相當簡單的問題,但我是C#,ASP.NET MVC3和ADO.Net實體框架的新手,我的朋友谷歌並沒有多大幫助我...在GET操作中設置實體鍵

所以,我有兩個實體:Post和Comments,它們之間有1-n的關係。

我想用一個簡單的表單發佈一條評論,並給出帖子的ID。

的GET部分(ID是文章的ID)

// 
    // GET: /Blog/Comment/5 

    public ActionResult Comment(int id) 
    { 
     Comment comment = new Comment(); 
     comment.PostReference.EntityKey = new EntityKey("BlogEntities.Posts", "id", id); 

     return View(comment); 
    } 

柱狀部件:

// 
    // POST: /Blog/Comment/5 

    [HttpPost] 
    public ActionResult Comment(Comment comment) 
    { 
     if (ModelState.IsValid) 
     { 
      db.Comments.AddObject(comment); 

      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 

     return View(); 
    } 

我參加了調試模式一坐,和它出現在鍵設置爲空當表單被提交。 如果我在HttpPost方法中設置了postreference,它可以正常工作,但我現在對這個id沒有任何線索。 所以,我認爲它必須設置在GET部分...

或者,也許我完全走錯了方向?

感謝您的任何幫助。

+0

GET參數中的關鍵是什麼?該頁面是否以/ Blog/Comment/n提交? – glenatron

+0

是的,的確,只是發現它......完全愚蠢的問題...... –

回答

0

正如之前所說的,完全愚蠢的問題...

// 
    // POST: /Blog/Comment/5 

    [HttpPost] 
    public ActionResult Comment(int id, Comment comment) 
    { 
     if (ModelState.IsValid) 
     { 
      db.Comments.AddObject(comment); 
      comment.PostReference.EntityKey = new EntityKey("BlogEntities.Posts", "id", id); 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 

     return View(); 
    } 

把ID的方法的阿根廷,然後設置參考ADDOBJECT的伎倆後...

希望能對大家幫助像我這樣一些迷失的鳥...