Asp.net mvc 3 即时加载未包括my repository类中的导航属性
我的repository类中有以下方法,用于检索Asp.net mvc 3 即时加载未包括my repository类中的导航属性,asp.net-mvc-3,entity-framework,Asp.net Mvc 3,Entity Framework,我的repository类中有以下方法,用于检索会话对象和关联的医学对象(通过使用。Include)定义即时加载),如下所示:- public Session GetSession(int id) { return entities.Sessions.Include(d => d.Medicine).FirstOrDefault(d => d.SessionID == id); } 调用上述存储库方法的我的操作方法如下所示:
会话
对象和关联的医学对象
(通过使用。Include
)定义即时加载),如下所示:-
public Session GetSession(int id)
{
return entities.Sessions.Include(d => d.Medicine).FirstOrDefault(d => d.SessionID == id);
}
调用上述存储库方法的我的操作方法如下所示:-
[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
我面临的问题是,在使用repository.Save()物理删除对象之后代码>,我将无法从内存访问Medicine navigation属性,并且将引发以下异常NullReferenceException未经用户代码在description=s.Medicine.Name
上处理,虽然我可以访问s.SessionID
,即使在删除对象后,它也会保存在内存中,但这是否意味着被删除的Session
对象没有包含(没有立即加载)Medicine
导航属性!!!?
BR如果删除与另一个实体有关系的实体,实体框架将同时删除这些对象之间的关系。您可以通过在删除实体之前为Json结果创建对象来解决此问题:
var s = repository.GetSession(id);
var result = new { IsSuccess = "True", id = s.SessionID,
description = s.Medicine.Name };
repository.DeleteSession(s);
repository.Save();
return Json(result, JsonRequestBehavior.AllowGet);
如果数据库中没有会话对Medicine的引用,这当然没有帮助,因为Include
不会返回相关对象。您必须单独处理此案例(只有在不需要关系的情况下才可能)。感谢您的回复,会话表(medicineId)中有一个外键,它引用了medicineId药物表的PK。