ASP.Net实体框架ObjectContext的错误实体、框架、错误、ASP

2023-09-02 02:04:10 作者:记住丶给妳幸福的人是Me

我要建一个4层ASP.Net Web应用程序。 该层是:

I'm building a 4 layered ASP.Net web application. The layers are:

在数据层 实体层 在业务层 在UI层

实体层我的数据模型类,并从(POCO),使用T4模板的datalayer我的实体数据模型(EDMX文件)所建。实体层中引用的所有其他层。

The entity layer has my data model classes and is built from my entity data model (edmx file) in the datalayer using T4 templates (POCO). The entity layer is referenced in all other layers.

我的数据层有一类称为SourceKeyRepository其中有一个功能,像这样:

My data layer has a class called SourceKeyRepository which has a function like so:

public IEnumerable<SourceKey> Get(SourceKey sk)
{
    using (dmc = new DataModelContainer())
    {
        var query = from SourceKey in dmc.SourceKeys
                    select SourceKey;

        if (sk.sourceKey1 != null)
        {
            query = from SourceKey in query
                    where SourceKey.sourceKey1 == sk.sourceKey1
                    select SourceKey;
        }

        return query;
    }
}

延迟加载被禁用,因为我不希望我的查询在此应用程序的其他层中运行。我试图访问这些信息在用户界面层时,收到以下错误:

Lazy loading is disabled since I do not want my queries to run in other layers of this application. I'm receiving the following error when attempting to access the information in the UI layer:

该ObjectContext的实例已   布置并且不能再用于   需要连接的操作。

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

我敢肯定,这是因为我的DataModelContainerDMC的处置。我怎样才能返回此IEnumerable的对象从我的数据层,以便它不依赖于ObjectContext中,而只是对数据模型?

I'm sure this is because my DataModelContainer "dmc" was disposed. How can I return this IEnumerable object from my data layer so that it does not rely on the ObjectContext, but solely on the DataModel?

有没有办法来限制延迟加载只发生在数据层?

Is there a way to limit lazy loading to only occur in the data layer?

推荐答案

查询是懒惰的值,因此数据不从数据库中retreived,直到你列举了。

query is lazy evaluated so the data is not retreived from the database until you enumerate it.

如果你这样做:

return query.ToList();

您会迫使要执行的查询,并避免此问题。

you will force the query to be executed and avoid the problem.

您收到错误消息,因为当主叫用户枚举集,ObjectContext中(DMC )是布置完毕感谢你的使用第(这是很好的 - 早处置与数据库相关的资源!)

You are receiving the error message because when the caller enumerates the collection, the ObjectContext (dmc) is already disposed thanks to your using clause (which is good - dispose database related resources early!)

在原来的岗位我用 AsEnumerable()我认为是正确的 - 直到我最近尝试使用它在这一确切的情况我自己。 AsEnumerable()只会使编译时类型转换 - 它不一一列举。要强制查询,以枚举它必须保存在列表或其他集合。

In the original post I used AsEnumerable() which I thought was correct - until I recently tried to use it in this exact situation myself. AsEnumerable() only makes a compile-time type conversion - it doesn't enumerate. To force the query to be enumerated it has to be saved in a List or other collection.