views:

272

answers:

1

I want to create new object with the FK reference on the entity in onother table. It's just a simple create view but i don't know how to reference the Research entity with 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  A: 

In .NET 3.5 SP 1:

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

In .NET 4.0, use FK associations instead.

Craig Stuntz
should i do this in data layer or in controler?
Ante B.
IMHO the controller really would do better to avoid having knowledge of the EF. So for the 3.5 solution, avoid doing it in the controller. OTOH, the 4.0 solution would work either place, as FK associations aren't really so EF-specific.
Craig Stuntz
tnx man, this really helps!
Ante B.