[英]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.