I am trying to use the stored procedure mapping feature in Entity Framework to perform the insert update and delete functions.
For whatever reason the procedures are not being called. They are correctly mapped, and supposedly all I have to do is call SaveChanges();
in my controller for them to execute.
Using this tutorial as a reference, what would I change about the Edit portion of the controller to have it utilize the stored procedure?
Tutorial Code:
//
// GET: /Home/Edit/5
public ActionResult Edit(int id)
{
var contactToEdit = (from c in _entities.ContactSet
where c.Id == id
select c).FirstOrDefault();
return View(contactToEdit);
}
//
// POST: /Home/Edit/5
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Contact contactToEdit)
{
if (!ModelState.IsValid)
return View();
try
{
var originalContact = (from c in _entities.ContactSet
where c.Id == contactToEdit.Id
select c).FirstOrDefault();
_entities.ApplyPropertyChanges(originalContact.EntityKey.EntitySetName, contactToEdit);
_entities.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
I thought that just by calling SaveChanges();
the update sproc would update so I just removed the call to ApplyPropertyChanges();
like so:
//
// POST: /Home/Edit/5
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Contact contactToEdit)
{
if (!ModelState.IsValid)
return View();
try
{
_entities.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
The update stored procedure doesn't execute though, I have sql profiler running to make sure.
The Programming Entity Framework book tutorials are quoted as saying:
Now that the stored procedures have been mapped, it is not necessary to call them directly in code. Any time SaveChanges is called, Entity Framework will use your mapped stored procedures for any required inserts, updates and deletes.
So, I figure I'm missing something fairly obvious here.
Edit, here is the exact version I'm working with now, the names are different:
//
// GET: /Candidate/Edit/5
public ActionResult Edit(int id)
{
var candidateToEdit = (from c in Internship.CompleteCandidate
where c.UserID == id
select c).FirstOrDefault();
//ViewData["EducationID"] = new SelectList(Internship.education.ToList(), "ID", "Category", candidateToEdit.EducationID);
return View(candidateToEdit);
}
//
// POST: /Candidate/Edit/5
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(CompleteCandidate candidateToEdit)
{
if (!ModelState.IsValid)
return View();
try
{
var originalCandidate = (from c in Internship.CompleteCandidate
where c.UserID == candidateToEdit.UserID
select c).FirstOrDefault();
Internship.ApplyPropertyChanges(originalCandidate.EntityKey.EntitySetName, candidateToEdit);
Internship.SaveChanges();
return RedirectToAction("Index");
}
catch(Exception e)
{
Response.Write("Error: " + e);
//return View();
return null;
}
}
}
}
It looks almost identical to the tutorial code in structure but throws a NullReference exception at runtime.