在我看到的 Entity Framework 数据访问的所有示例中,每个方法都有自己的 using
block ,如下所示。
是否有替代方法?比如上下文对象是否可以只是一个类成员,比如:
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
语句中或在 DaoClass
的实例上调用 Dispose()
。
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();
}
}
关于c# - 替代多个使用 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53091732/