声明数据库变量的良好做法

本文关键字:数据库 变量 声明 | 更新日期: 2024-10-18 15:30:16

大多数时候,当我处理与数据库相关的对象时,我都是这样工作的:

// Declare a private static variable of my database
private static BlueBerry_MTGEntities mDb = new BlueBerry_MTGEntities();

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

public StoreInfo GetStoreByID(int _storeID)
{
    using (mDb = new BlueBerry_MTGEntities())
    {
        mDb.Database.Connection.Open();
        // Bla bla stuff to return the proper StoreInfo Object.
    }
}

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

声明数据库变量的良好做法

如果要在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.
    }
}

若要在using语句之外使用mDb,则可以声明它,但不必实例化它(使用new关键字)

您不应该这样做——这是对static功能的滥用。

您的方法的问题是,在StoreInfo类的生命周期中,mDb在任何地方、任何时间都可见,但它仅在执行using块时有效。一旦您的程序存在using块,您的mDb变量将变为无效,但它保持为非空,因此没有明显的方法来检查其有效性。因此,任何在using块之外使用此变量的人都有访问已处理对象并触发异常的风险。

使mDb成为一个常规的局部变量,并确保其范围仅限于using块,如下所示:

using (var mDb = new BlueBerry_MTGEntities())
{
    mDb.Database.Connection.Open();
    // Bla bla stuff to return the proper StoreInfo Object.
}