Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
872 views
in Technique[技术] by (71.8m points)

.net - ASP.Net Entity Framework, objectcontext error

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

  1. Data Layer
  2. Entity Layer
  3. Business Layer
  4. UI Layer

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.

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:

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

If you do:

return query.ToList();

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

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!)

Edit

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...