Skip to content

Instantly share code, notes, and snippets.

@robertmuehsig
Created June 18, 2013 06:44
Show Gist options
  • Save robertmuehsig/5803137 to your computer and use it in GitHub Desktop.
Save robertmuehsig/5803137 to your computer and use it in GitHub Desktop.
EF 6.0 Beta Seed/DbMigrationsConfig behaviour
// democode in Application_Start from an MVC app
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
using (var context = new AppDbContext("Data Source=server;Initial Catalog=db;User ID=dbuser;Password=pw;MultipleActiveResultSets=True"))
{
Database.SetInitializer<AppDbContext>(new DropAndCreateDatabaseDbInitializer());
context.Database.Initialize(true);
}
using (var context = new AppDbContext("Data Source=server;Initial Catalog=db;User ID=dbuser;Password=pw;MultipleActiveResultSets=True"))
{
var test = context.Items.ToList();
}
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
// Magically called - this is used by other code parts, we "dont" need it for creating the database
public class EfMigrationConfig : DbMigrationsConfiguration<AppDbContext>
{
public EfMigrationConfig()
{
ContextKey = "Default";
AutomaticMigrationsEnabled = false;
AutomaticMigrationDataLossAllowed = false;
}
}
// Strategy with seed
public class DropAndCreateDatabaseDbInitializer : DropCreateDatabaseAlways<AppDbContext>
{
protected override void Seed(AppDbContext context)
{
context.Items.Add(new Items() { Id = Guid.NewGuid(), Value = "Test" }); // <-- Exception "The underlying provider failed on Open."
// no database created, why?
context.SaveChanges();
}
}
// sample context
public class AppDbContext : DbContext
{
public AppDbContext()
: base()
{
}
public AppDbContext(string connectionString)
: base(connectionString)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// table name will now be equal to the class names
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
public DbSet<Items> Items { get; set; }
}
public class Items
{
public Guid Id { get; set; }
public string Value { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment