声明数据库变量的好习惯

hsi*_*sim 4 c# asp.net asp.net-mvc entity-framework

大多数时候,当我使用数据库相关对象时,我的工作方式如下:

// Declare a private static variable of my database
private static BlueBerry_MTGEntities mDb = new BlueBerry_MTGEntities();
Run Code Online (Sandbox Code Playgroud)

然后,在任何方法(示例)中:

public StoreInfo GetStoreByID(int _storeID)
{
    using (mDb = new BlueBerry_MTGEntities())
    {
        mDb.Database.Connection.Open();

        // Bla bla stuff to return the proper StoreInfo Object.
    }
}
Run Code Online (Sandbox Code Playgroud)

以这种方式工作以避免汇集崩溃并开发高效的MVC Asp.Net应用程序是一种好习惯吗?如果没有,那么什么是好的做法,你会怎么做?

Hab*_*bib 5

如果要在语句中使用它,则不必实例化它(甚至声明它)using.

public StoreInfo GetStoreByID(int _storeID)
{
    using (BlueBerry_MTGEntities mDb = new BlueBerry_MTGEntities())
    {
        mDb.Database.Connection.Open();

        // Bla bla stuff to return the proper StoreInfo Object.
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你打算mDb在using语句之外使用,那么你可以只声明它,但你不必实例化它(使用new关键字).