简体   繁体   English

EntityFramework中的ObjectDisposedException

[英]ObjectDisposedException in EntityFramework

I have this class and i often(but not always) get NullReferenceException or ObjectDisposedException when use method ExecuteQuery: 我有这个类,当使用方法ExecuteQuery时,我经常(但不总是)得到NullReferenceException或ObjectDisposedException:

public class Dao
{
    protected StoreDbContext Context = new StoreDbContext();

    public IEnumerable<T> ExecuteQuery<T>(string query, params object[] parameters)
    {
        return  Context.Database.SqlQuery<T>(query, parameters).ToList();
    }

}

but, if if i will create Context in method i don't get any exception. 但是,如果我将在方法中创建Context,我不会得到任何异常。 Why? 为什么?

public class Dao
{
    protected StoreDbContext Context = new StoreDbContext();

    public IEnumerable<T> ExecuteQuery<T>(string query, params object[] parameters)
    {
        return  new StoreDbContext().Database.SqlQuery<T>(query, parameters).ToList();
    }

}

Don't keep the StoreDbContext hanging around when doing updates. 进行更新时不要让StoreDbContext保持不变。 It will end up with stale data/entities in it. 最终会有过时的数据/实体。 The accepted pattern is to fire up a new Context for a unit of work/scoped set of operations. 接受的模式是为工作单元/范围操作集启动新的上下文。 The second example might be acceptable, but you need to ensure you dispose of the context by creating it with a using statement. 第二个示例可能是可接受的,但您需要确保通过使用using语句创建上下文来处置它。 Refactor the method to account for this. 重构方法以解决此问题。

I tend to keep search results in a separate context with no tracking (read only) but would use a fresh context for updates, as I'm using WCF Data Services. 我倾向于将搜索结果保存在单独的上下文中,没有跟踪(只读),但会使用新的上下文进行更新,因为我正在使用WCF数据服务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM