jmasterx
jmasterx

Reputation: 54183

Close connections to DB with LINQ?

I have some code to auto delete and renew a database using LINQ.

KezberPMDBDataContext db = new KezberPMDBDataContext();
if (!db.DatabaseExists())
{
    db.DeleteDatabase();
}
db.CreateDatabase();

However, it sometimes fails due to open copnnections. In SQL Management Studio, I can force it to kill the connections but I see no such option in LINQ.

Does anyone know of a way to do this?

Upvotes: 2

Views: 3367

Answers (2)

vivek shukla
vivek shukla

Reputation: 1

you can use some code for close current connection of sql server in LINQ

DBDataContext db= new DBDataContext ();

after complete your action you can dispose the db

db.Dispose();

Upvotes: -2

Javiere
Javiere

Reputation: 1651

DataContext should always be "destroyed" or Disposed, so optimally you should use the Context object inside an using statement:

 using(KezberPMDBDataContext db = new KezberPMDBDataContext())
 {
    if (!db.DatabaseExists())
    {
        db.DeleteDatabase();
    }
    db.CreateDatabase();
  }

This will automatically dispose the context after using it.

To directly dispose it, call the method:

 db.Dispose();

Upvotes: 4

Related Questions