c# - 替代多个使用 block

标签 c# .net entity-framework

在我看到的 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/

相关文章:

c# - 为什么 HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath 在不同的服务器上不同?

c# - 理解正确的 http keep-alive 实现

c# - 跟踪 Entity Framework 进度

c# - ASP.NET FormsAuthentication - 要解密的数据长度无效

c# - Entity Framework IDENTITY_INSERT

c# - 在 ASP.Net MVC5 中从两个 EF 模型创建 ViewModel

C# 使每个面板在单独的 View 中

c# - 如何使 Winforms 中的按钮控件变灰/禁用?

c# - 如何在c#中解析json字符串

c# - 如何从从另一个文件夹中加载的程序集中获取类型?