简体   繁体   English

通过实体模型访问数据库的类,如何清理连接?

[英]Class for DB access via an Entity Model, how to cleanup the connection?

I have a class I'm using to handle all my DB interaction. 我有一个用于处理所有数据库交互的类。 Basically when an instance of this class is created it creates an instance of the model, which will persist until the DataAccess object is out of scope. 基本上,在创建此类的实例时,它将创建模型的实例,该实例将一直存在,直到DataAccess对象超出范围为止。

public class DataAccess
{
    ModelContainer model;

    public DataAccess()
    {
        model = new ModelContainer();
    }

    public void Close()
    {
        if (model != null)
        {
            model.Connection.Close();
            model.Dispose();
        }
    }
}

What cleanup do I need to preform on the model? 我需要对模型进行什么清理? I've cought my self forgetting to call my Close() method when writing my unit tests. 我已经在编写单元测试时忘了调用自己的Close()方法,这让我很担心。 I like the using(DataAccess data = new DataAccess()) way of dealing with DB objects like you use in LINQ to SQL, so should I make DataAccess implement iDisposeable? 我喜欢using(DataAccess data = new DataAccess())处理LINQ to SQL中使用的DB对象的方式,所以我应该使DataAccess实现iDisposeable吗?

If you have items in the class that implements IDisposable it is a good idea to make your class implement that aswell so that they get disposad properly. 如果您的类中有实现IDisposable的项目,则最好让您的类也实现该项目,以使它们得到正确的处置。 If you do not call them upon disposing your class you might have some unexcepted memory leaks. 如果在处置类时未调用它们,则可能会发生一些异常的内存泄漏。 And it's easy to write "using" as you mentioned which you only can do when you implement IDisposable. 正如您所提到的,编写“使用”很容易,只有实现IDisposable时才能做到。

This is an excellent example on how to implenet IDisosable: http://msdn.microsoft.com/en-us/library/system.idisposable.aspx 这是一个有关如何实现IDisosable的极好的示例: http : //msdn.microsoft.com/zh-cn/library/system.idisposable.aspx

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

相关问题 通过Entity Framework 5将复杂模型保存到DB - Saving a complex model to DB via Entity Framework 5 与开放访问实体模型的多重连接 - Multiple connection with Open access entity model 为单元测试目的实例化没有数据库连接的空实体模型 - Instantiating an empty Entity Model without a DB connection for Unit Testing purposes 当实体框架模型在专用的类库中时,如何在C#应用程序中定义连接字符串和数据库提供程序? - How to define connection string and database provider in an C# application when the Entity Framework model is in a dedicated class library? 如何获取实体模型连接字符串? - How to fetch entity model connection string? 如何通过WCF从实体数据模型公开单个类 - How can I expose a single class from Entity Data Model via WCF 实体框架 - 如何不将继承的类添加到db - Entity Framework - how not to add inherited class to the db 如何在实体框架模型的局部类中访问已加载的数据 - How to access loaded data within an entity framework model's partial class 如何重写基类的数据库连接字符串? - How to override a base class' DB connection string? 如何以编程方式更改数据库连接c#Entity Framework - How to change db connection programmatically c# Entity Framework
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM