Skip to content

Instantly share code, notes, and snippets.

@jrusbatch
Created March 23, 2017 16:56
Show Gist options
  • Save jrusbatch/c51e614e6f715b2ed6eeb755fa03e138 to your computer and use it in GitHub Desktop.
Save jrusbatch/c51e614e6f715b2ed6eeb755fa03e138 to your computer and use it in GitHub Desktop.
public static class DatabaseFactory
{
private static ISqlLocalDbInstance GetInstance()
{
var provider = new SqlLocalDbProvider();
return provider.GetInstance("v13.0");
}
public static IDatabase CreateDatabase()
{
var instance = GetInstance();
var dbName = Guid.NewGuid().ToString("N");
instance.Start();
var builder = instance.CreateConnectionStringBuilder();
builder.SetInitialCatalogName(dbName);
var connectionString = builder.ConnectionString;
return new TestDatabase(instance, dbName);
}
private class TestDatabase : IDatabase
{
private readonly ISqlLocalDbInstance instance;
public TestDatabase(ISqlLocalDbInstance dbInstance, string dbName)
{
instance = dbInstance;
Name = dbName;
}
public string Name { get; }
public DbConnection CreateConnection()
{
var builder = instance.CreateConnectionStringBuilder();
builder.InitialCatalog = Name;
return new SqlConnection(builder.ConnectionString);
}
public void Dispose()
{
instance.DropDatabase(Name);
}
}
}
public interface IDatabase : IDisposable
{
string Name { get; }
DbConnection CreateConnection();
}
internal static class SqlLocalDbInstanceExtensions
{
public static void CreateDatabase(this ISqlLocalDbInstance instance, string name)
{
if (instance == null)
throw new ArgumentNullException(nameof(instance));
if (string.IsNullOrEmpty(name))
throw new ArgumentException("Value cannot be null or empty", nameof(name));
var fileName = Path.Combine(Environment.CurrentDirectory, name + ".mdf");
using (var connection = instance.CreateConnection())
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText =
Invariant($"CREATE DATABASE [{name}] on (name='{name}', filename='{fileName}');");
command.ExecuteNonQuery();
}
}
}
public static void DropDatabase(this ISqlLocalDbInstance instance, string name)
{
if (instance == null)
throw new ArgumentNullException(nameof(instance));
if (string.IsNullOrEmpty(name))
return;
using (var connection = instance.CreateConnection())
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText =
Invariant($"ALTER DATABASE [{name}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [{name}];");
command.ExecuteNonQuery();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment