Skip to content

Instantly share code, notes, and snippets.

@WizzApp
Created September 5, 2012 11:39
Show Gist options
  • Save WizzApp/3635399 to your computer and use it in GitHub Desktop.
Save WizzApp/3635399 to your computer and use it in GitHub Desktop.
Base class for db integration tests with EF and xUnit
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<!-- This parameter must match with the parameter in the entity connection string below -->
<add key="Database" value="TestDB" />
</appSettings>
<connectionStrings>
<add name="ObjectContext" connectionString="metadata=res://*/Entities.csdl|res://*/Entities.ssdl|res://*/Entities.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=(local);Database=TestDB;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework&quot;" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
using System;
using System.Configuration;
using System.Data.Objects;
using System.Data.SqlClient;
namespace Varta.VartaGuide.Tests.Integration
{
public class EFDatabaseTest<CONTEXTTYPE> where CONTEXTTYPE:ObjectContext, new()
{
public DbContext DbContext { private set; get; }
public EFDatabaseTest()
{
DbContext = new DbContext();
string database = ConfigurationManager.AppSettings.Get("Database");
// Create db if necessary
var con = new System.Data.SqlClient.SqlConnection(
String.Format("Data Source={0};Integrated Security=SSPI;",
DbContext.Connection.DataSource));
con.Open();
System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand("SELECT name FROM sys.databases WHERE name = @dbName");
command.Connection = con;
var param = command.CreateParameter();
param.ParameterName = "@dbName";
param.Value = database;
command.Parameters.Add(param);
var reader = command.ExecuteReader();
bool databaseExists = reader.HasRows;
reader.Close();
if (databaseExists)
{
var commandCreateDb = new SqlCommand(String.Format("DROP DATABASE {0}", database));
commandCreateDb.Connection = con;
commandCreateDb.ExecuteNonQuery();
}
con.Close();
DbContext.CreateDatabase();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment