Entity的导航属性在View中使用,但是该Entity所在的Context已经在Controller中通过 using 释放掉;但是Entity又具有Deferred Query Evaluation性质,因此,导航属性对象没有被加载,从而出现上述错误。
解决方案
认真学习msdn教程
解决方法一:How to: Explicitly Load Related Objects
禁用Context的Deferred Query Evaluation,然后在查询结束后手动加载所有需要的导航属性
context.ContextOptions.LazyLoadingEnabled =
false
;
if
(!contact.SalesOrderHeaders.IsLoaded)
{
contact.SalesOrderHeaders.Load();
}
|
解决方法二:How to: Use Query Paths to Shape Results
在查询中声明包含导航属性
var
contacts = (
from
contact
in
context.Contacts
.Include(
"SalesOrderHeaders.SalesOrderDetails"
)
select
contact).FirstOrDefault();
|