I have the same problem and I was thinking about how to deal with it.
There are 2 approaches.
(1) Disconnect at the end (or during) the database
I did not find a way to close the connection in LinqToSQL, but in fact it is not needed. Just execute the following code:
var db = @"c:\blablabla\database1.mdf"; using (var master = new DataContext(@"Data Source=(LocalDB)\v11.0;Initial Catalog=master;Integrated Security=True")) { master.ExecuteCommand(@"ALTER DATABASE [{0}] SET OFFLINE WITH ROLLBACK IMMEDIATE", db); master.ExecuteCommand(@"exec sp_detach_db '{0}'", db); }
and make sure nothing tries to execute the db request after (or you reconnect it).
(2) Disconnect at startup
Before you connect to db , disconnecting will be as simple as:
var db = @"c:\blablabla\database1.mdf"; using (var master = new DataContext(@"Data Source=(LocalDB)\v11.0;Initial Catalog=master;Integrated Security=True")) master.ExecuteCommand(@"exec sp_detach_db '{0}'", db);
This costume is very suitable for my needs, because I do not care about the delay to launch the application (because in this case I will have to bind to db always), but it will fix any type
System.Data.SqlClient.SqlException (0x80131904): Database 'c: \ blablabla \ database1.mdf' already exists. Choose a different database name.
which occurs if the database file is deleted and you try to create it programmatically
// DataContext if (!DatabaseExists()) CreateDatabase();
Another way
You can also run the sqllocaldb command-line sqllocaldb as follows:
var start = new ProcessStartInfo("sqllocaldb", "stop v11.0"); start.WindowStyle = ProcessWindowStyle.Hidden; using (var stop = Process.Start(start)) stop.WaitForExit(); start.Arguments = "delete v11.0"; using (var delete = Process.Start(start)) delete.WaitForExit();
It will stop the server by canceling all databases. If you have another application using localDB, the next time they will experience a delay when trying to execute the request.