ASP.NET 4.0 MVC 2.0 EF 4.0
For my code below, the view accesses a navigation property on the img and is throwing a null reference exception when the database cannot perform the operation. This happens with both .Include on the context and LazyLoadingEnabled==true. My navigation property becomes null right after SaveChanges. But SaveChanges fails because of a foreign key restraint in the database, a pretty common scenario. It's typical to redisplay the form along with the error message, but the navigation property is permanently null. Anyone know how to fix this?
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
context.ContextOptions.LazyLoadingEnabled = true;
var img = GetImageByID(id);
try
{
context.DeleteObject(img);
context.SaveChanges();
return RedirectToAction("Index");
}
catch
{
ModelState.AddModelError("", "Cannot delete object");
}
return View(img);
}