Ante
Ante

Reputation: 8637

Using of Object Reference in Entity Framework

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

Upvotes: 0

Views: 1363

Answers (1)

Craig Stuntz
Craig Stuntz

Reputation: 126587

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.

Upvotes: 1

Related Questions