ASP.Net Entity Framework, objectcontext error

旧街凉风 提交于 2019-11-29 13:19:15

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.

You could call some method on the query object, for example

return query.AsEnumerable();

That should make sure you execute the query, thus making sure you don't need the object context later.

Don't use

return query.AsEnumerable();

use

return query.ToArray();

before disposing your context.

Returning AsEnumerable won't execute the foreach until the object is referenced. Converting it to an array ensures the foreach executes before your object is disposed. You may put your context in a using block (something you should do) then.

In my opinion, this scenario has no relevance with AsEnumerable() or AsQueryable(). Try this;

 public IEnumerable<SourceKey> Get(SourceKey sk, DataModelContainer dmc) {    

    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;

}

And you must get this property with

using (dmc = new DataModelContainer()) {
 // GET
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!