I have the following method inside my repository class, to retrieve a Session object and the associated Medicine object (by defining Eager loading using the .Include) as shown below:-
public Session GetSession(int id)
{
return entities.Sessions.Include(d => d.Medicine).FirstOrDefault(d => d.SessionID == id);
}
My action method which call the above repository method look as follow:-
[HttpPost]
public ActionResult Delete(int id)
{
try
{
//string desc;
var s = repository.GetSession(id);
repository.DeleteSession(s);
repository.Save();
return Json(new { IsSuccess = "True", id = s.SessionID, description = s.Medicine.Name }, JsonRequestBehavior.AllowGet);
}
catch (ArgumentNullException)
//code goes here
The problem i am facing is that after physically deleting the object using repository.Save(); ,, i will not be able to access the Medicine navigation property from the memory and the following exception will be raised NullReferenceException was unhandled by user code on description = s.Medicine.Name , while i can access the s.SessionID which will be avilable in the memory even after deleting the object, so does this means that the Session object which was deleted did not Include (did not eager load) the Medicine navigation property !!!?
BR
If you delete an entity which has a relationship to another entity, Entity Framework will remove the relationship between those objects at the same time. You can solve the problem by creating the object for the Json result before you delete the entity:
If there is no reference from the session to Medicine in the database this won’t help of course because
Includewon’t return a related object. You have to handle this case separately (it would be only possible if the relationship is not required).