2009-08-20 29 views
0

我想用其他表上的實體的FK引用創建新對象。這只是一個簡單的創建視圖,但我不知道如何引用ID == ID的研究實體。在實體框架中使用對象引用

public ActionResult Create(int id) 
    { 
     SurveyPaper surveyPaper = new SurveyPaper(); 

     return View(surveyPaper); 
    } 

    [AcceptVerbs(HttpVerbs.Post)] 
    public ActionResult Create(int id, FormCollection collection) 
    { 
     var surveyPaper = new SurveyPaper(); 

     try { 
      UpdateModel(surveyPaper); 
      surveyPaper.Research.ResearchID = id; 
      _r.AddSurveyPaper(surveyPaper); 

      return RedirectToAction("Details", new { id = surveyPaper.SurveyPaperID }); 
     } 
     catch { 
      return View(surveyPaper); 
     } 
    } 

回答

1

在.NET 3.5 SP 1:

// obviously, substitute your real entity set and context name below 
surveyPaper.ResearchReference.EntityKey = 
    new EntityKey("MyEntities.ResearchEntitySetName", "ResearchID", id); 

在.NET 4.0,使用FK協會代替。

+0

我應該這樣做在數據層或控制器? – Ante 2009-08-20 13:29:13

+0

恕我直言,控制器真的會做得更好,以避免瞭解EF的知識。因此,對於3.5解決方案,請避免在控制器中執行此操作。 OTOH,4.0解決方案可以在任何地方工作,因爲FK協會並不是特別針對EF的。 – 2009-08-20 13:38:17

+0

tnx男人,這真的有幫助! – Ante 2009-08-20 13:40:50