C# 使用Include时ObjectContext关闭错误?

C# 使用Include时ObjectContext关闭错误?,c#,linq,entity-framework,objectquery,C#,Linq,Entity Framework,Objectquery,我正在尝试为实体框架创建一个通用的Get方法,使用动态的Where和Include。我正在使用下面的代码,但是当我尝试访问包含列表中的导航属性时,我得到一个关于关闭对象上下文的错误 .Include()是否应该加载这些对象,这样我就不需要保持ObjectContext的打开状态 public static List<T> GetList<T>(Func<T, bool> where, string[] includes) where T : Entit

我正在尝试为实体框架创建一个通用的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();
    }
}
公共静态列表GetList(Func其中,字符串[]包括)
其中T:EntityObject
{
使用(var context=new TContext())
{
ObjectQuery q=context.CreateObjectSet();
foreach(包含中的字符串navProperty)
{
q、 包括(不动产);
}
返回q.Where(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
var x=DAL.GetList(
p=>p.Id==1
,新字符串[]{“类型”});
变量y=x.Type;//抛出上下文已关闭的错误

我觉得我在这里一定犯了一些愚蠢的错误,因为我是EF的新手,并且仍在努力解决它。

您没有重新分配
q
-这应该可以解决它:

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

请记住,您正在使用扩展方法,每个扩展方法都返回一个新的
IQueryable
,而不是修改原始的。

Oh…>我就知道会是那样的愚蠢,谢谢你