Sto cercando di creare un DbContextInitializer e stavo ereditando da DropCreateDatabaseAlways <> tuttavia non funzionava come desiderato.
public void InitializeDatabase(DbContext context)
{
if (context.Database.Exists())
{
context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction,
$"ALTER DATABASE [{context.Database.Connection.Database}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
context.Database.Delete();
context.Database.Create();
}
else
{
context.Database.Create();
}
}
Il problema è quando arriva a ExecuteSqlCommand tenta di rilasciare il database prima di eseguire il comando (debugging con SQL Profiler)
Qualcuno potrebbe farmi sapere come eseguire
ALTER DATABASE [{context.Database.Connection.Database}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
prima che provi a eliminare il database?
A proposito, il comando dop viene inviato quando colpisce la riga ExecuteSqlCommand.
È sufficiente utilizzare il comando SQL C #:
System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder(connectionString);
string database = builder.InitialCatalog;
using(SqlConnection con = new SqlConnection(Connectionstring))
{
con.Open();
String sqlCommandText = @"
ALTER DATABASE " + database + @" SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
DROP DATABASE [" + database + "]";
SqlCommand sqlCommand = new SqlCommand(sqlCommandText, con);
sqlCommand.ExecuteNonQuery();
}
Aggiornamento: questo script ucciderà tutti i processi in esecuzione e quindi eliminerà il database che ho appena testato e funziona:
using (var con = new SqlConnection(@"Server =.\; Database = UsersDatabase; Integrated Security = True; "))
{
con.Open();
var sqlCommandText = @"USE master
DECLARE @kill varchar(8000) = '';
SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), spid) + ';'
FROM master..sysprocesses
WHERE dbid = db_id('UsersDatabase')
EXEC(@kill);
ALTER DATABASE UsersDatabase SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
drop database UsersDatabase";
var sqlCommand = new SqlCommand(sqlCommandText, con);
sqlCommand.ExecuteNonQuery();
}
Il mio nome di database è UsersDatabase e il mio SQL Server è. \ Devi cambiarli! appena codificato il nome del database / server per il test e dopo il test è possibile leggere la stringa di connessione dal file di configurazione come la descrizione nella sezione precedente.