使用 Include 时出现 ObjectContext Closed 错误?
我正在尝试为实体框架创建一个通用的 Get 方法,其中包含动态 Where
和 Include
。我正在使用下面的代码,但是当我尝试访问包含列表中的导航属性时,我收到有关对象上下文被关闭的错误
不是 .Include()
应该加载这些对象,这样我就不需要保持 ObjectContext 打开?
public static List<T> GetList<T>(Func<T, bool> where, string[] includes)
where T : EntityObject
{
using (var context = new TContext())
{
ObjectQuery<T> q = context.CreateObjectSet<T>();
foreach (string navProperty in includes)
{
q.Include(navProperty);
}
return q.Where<T>(where).ToList();
}
}
导致错误的代码:
var x = DAL<MyContext>.GetList<MyEntity>(
p => p.Id == 1
, new string[]{ "Type" } );
var y = x.Type; // Throws an error that context has been closed
我觉得我一定犯了某种愚蠢的错误,因为我是 EF 的新手,并且仍在尝试解决它。
I am trying to create a generic Get method for Entity Framework, with a dynamic Where
and Include
. I am using the code below, however when I try to access a Navigation Property that was in the Include list, I am getting an error about the Object Context being closed
Isn't .Include()
supposed to load those objects so I don't need to keep the ObjectContext open?
public static List<T> GetList<T>(Func<T, bool> where, string[] includes)
where T : EntityObject
{
using (var context = new TContext())
{
ObjectQuery<T> q = context.CreateObjectSet<T>();
foreach (string navProperty in includes)
{
q.Include(navProperty);
}
return q.Where<T>(where).ToList();
}
}
Code causing error:
var x = DAL<MyContext>.GetList<MyEntity>(
p => p.Id == 1
, new string[]{ "Type" } );
var y = x.Type; // Throws an error that context has been closed
I feel I must be making some kind of stupid mistake here because I'm new to EF and am still trying to figure it out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您没有重新分配
q
- 这应该可以解决这个问题:请记住,您使用的扩展方法每个都返回一个 new
IQueryable
,不修改原来的。You are not re-assigning
q
- this should fix it:Remember you are using extension methods that each return a new
IQueryable<T>
, not modifying the original.