在实体框架中使用对象引用

时间:2009-08-20 12:21:58

标签: asp.net-mvc entity-framework

我想在另一个表的实体上使用FK引用创建新对象。它只是一个简单的创建视图,但我不知道如何使用ID == id。

引用Research实体
    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 个答案:

答案 0 :(得分: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关联。