我有这个类,我经常(但不总是)在使用方法 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();
}
}
但是,如果我将在方法中创建上下文,我不会得到任何异常。为什么?
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();
}
}