Пример #1
0
        private static SqlServerInstance CreateInstance()
        {
            var instance = new SqlServerInstance();

            var database = $"{Guid.NewGuid().ToString("N").ToUpperInvariant()}";
            var builder  = new SqlConnectionStringBuilder("Data Source=(localdb)\\MSSQLLocalDB;Integrated Security=true;")
            {
                InitialCatalog = "master"
            };

            using (var connection = new SqlConnection(builder.ConnectionString))
            {
                connection.Open();
                connection.Execute($"CREATE DATABASE [{database}] ON (NAME = N'{database}', FILENAME = '{Path.Combine(EnsureOutputDir(), database)}.mdf')");
                connection.Execute($"ALTER DATABASE [{database}] SET READ_COMMITTED_SNAPSHOT ON;");
                connection.Execute($"ALTER DATABASE [{database}] SET ALLOW_SNAPSHOT_ISOLATION ON;");
            }

            builder.InitialCatalog = database;

            instance.Database         = database;
            instance.ConnectionString = builder.ConnectionString;
            instance.FileName         = $"{Path.Combine(EnsureOutputDir(), database)}.mdf";

            return(instance);
        }
Пример #2
0
        private static void DisposeInstance(SqlServerInstance instance)
        {
            var builder = new SqlConnectionStringBuilder(instance.ConnectionString)
            {
                InitialCatalog = "master"
            };

            using (var db = new SqlConnection(builder.ConnectionString))
            {
                db.Open();
                try
                {
                    db.Execute($"ALTER DATABASE [{instance.Database}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
                    db.Execute($"DROP DATABASE [{instance.Database}]");
                }
                catch (SqlException)
                {
                }
            }

            File.Delete(Path.Combine(EnsureOutputDir(), $"{instance.Database}.mdf"));
        }