Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good practice to declare database variable

Most of the times when I working with database related object I work like this:

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

Then, in any method (example):

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

        // Bla bla stuff to return the proper StoreInfo Object.
    }
}

Is is good practice to work this way to avoid pooling crashes and to develop an efficient MVC Asp.Net application? If not, what would be the good practices, and how would you do it?

like image 512
hsim Avatar asked Jan 12 '23 16:01

hsim


1 Answers

You don't have to instantiate it (or even declare it) if you are going to use it inside using statement.

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.
    }
}

If you are going to use mDb outside of using statement then you can just declare it but you don't have to instantiate it (with new keyword).

like image 96
Habib Avatar answered Jan 18 '23 05:01

Habib