使用 Include 时出现 ObjectContext Closed 错误?

发布于 2024-12-01 06:56:51 字数 913 浏览 0 评论 0原文

我正在尝试为实体框架创建一个通用的 Get 方法,其中包含动态 WhereInclude。我正在使用下面的代码,但是当我尝试访问包含列表中的导航属性时,我收到有关对象上下文被关闭的错误

不是 .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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

苏璃陌 2024-12-08 06:56:51

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

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

请记住,您使用的扩展方法每个都返回一个 new IQueryable,不修改原来的。

You are not re-assigning q - this should fix it:

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

Remember you are using extension methods that each return a new IQueryable<T>, not modifying the original.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文