在我看到的用于Entity Framework数据访问的所有示例中,每个方法都有自己的using
块,如下所示。
是否有替代方法?例如,上下文对象可以只是一个类成员,例如:
MyModelContext context = new MyModelContext();
是否有理由为DAO类中的每个方法创建一个新的上下文对象?
public class DaoClass
{
public void DoSomething()
{
using (var context = new MyModelContext())
{
// Perform data access using the context
}
}
public void DoAnotherThing()
{
using (var context = new MyModelContext())
{
// Perform data access using the context
}
}
public void DoSomethingElse()
{
using (var context = new MyModelContext())
{
// Perform data access using the context
}
}
}
最佳答案
您可以使用DaoClass
实现IDisposable
并将上下文作为类的属性。只要确保将DaoClass
包装在using
语句中,或在Dispose()
实例上调用DaoClass
。
public class DaoClass : IDisposable
{
MyModelContext context = new MyModelContext();
public void DoSomething()
{
// use the context here
}
public void DoAnotherThing()
{
// use the context here
}
public void DoSomethingElse()
{
// use the context here
}
public void Dispose()
{
context.Dispose();
}
}