我想在實體框架中使用存儲過程映射功能來執行插入更新和刪除功能。存儲過程沒有調用實體框架使用asp.net MVC
由於種種原因程序沒有被調用。它們被正確映射,並且據說我所要做的就是在我的控制器中調用SaveChanges();
來執行它們。
使用this tutorial作爲參考,我將更改控制器的「編輯」部分以使其使用存儲過程?
教程代碼:
//
// 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();
}
}
}
我認爲,只要通過喚起SaveChanges();
更新存儲過程將更新,所以我只是刪除了呼叫ApplyPropertyChanges();
像這樣:
//
// 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();
}
}
}
更新存儲過程沒有按」噸執行雖然,我有SQL分析器運行確保。
的編程實體框架書籍教程被引述說:
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.
所以,我想我失去了一些東西很明顯這裏。
編輯,這裏是我與現在的工作的確切版本,名稱不同:
//
// 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;
}
}
}
}
它看起來幾乎相同的教程代碼結構,但在運行時會引發NullReference例外。
感謝您的回覆,我已經更新了上面的代碼,並使用了目前基於上述教程提供的確切版本。 當我把
ApplyPropertyChanges();
調用我得到一個NullReference異常。 – 2009-06-26 20:12:59