2011-08-23 37 views
1

我正在尝试为实体框架创建一个通用Get方法,其中动态为WhereInclude。我使用下面的代码,但是当我尝试访问包含列表中的导航属性时,出现关于对象上下文被关闭的错误ObjectContext使用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和我仍然在试图弄明白。

回答

3

你是不是重新分配q - 这应该修复它:

foreach (string navProperty in includes) 
    { 
     q = q.Include(navProperty); 
    } 

记住,你正在使用的扩展方法,每个返回IQueryable<T>,不修改原始。

+0

哦...><我知道这会是一件愚蠢的事情,谢谢 – Rachel