Skip to content

Instantly share code, notes, and snippets.

@reyronald
Created January 4, 2018 18:10
Show Gist options
  • Save reyronald/96203741f283ec4a9c6d21a6a2c0c079 to your computer and use it in GitHub Desktop.
Save reyronald/96203741f283ec4a9c6d21a6a2c0c079 to your computer and use it in GitHub Desktop.
Useful Entity Framework's DbContext Database Initializers
using Boundaries.Persistence.Contexts;
using Boundaries.Persistence.Migrations;
using System.Data.Entity;
using Validation;
namespace DatabaseInitializers
{
public sealed class DropCreateDatabaseAlwaysAndSeed : DropCreateDatabaseAlways<MyDbContext>
{
public override void InitializeDatabase(MyDbContext context)
{
Requires.NotNull(context, nameof(context));
// This tells the database to close all connections and rolback open transactions.
// The intent to avoid any open database connections errors during database drop.
if (context.Database.Exists())
{
context.Database.ExecuteSqlCommand(
TransactionalBehavior.DoNotEnsureTransaction,
$"ALTER DATABASE [{context.Database.Connection.Database}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
}
base.InitializeDatabase(context);
}
protected override void Seed(MyDbContext context)
{
// Seed here...
}
}
}
using System.Data.Entity;
using Validation;
namespace DatabaseInitializers
{
/// <summary>
/// Drops the database on application startup (the first time only), recreates it based on the model's
/// schema and nothing more. It does NOT add any seed data, so the resulting application will have
/// an empty database.
/// </summary>
/// <typeparam name="T"></typeparam>
public sealed class ForceDropCreateDatabaseAlways : DropCreateDatabaseAlways<MyDbContext>
{
public override void InitializeDatabase(MyDbContext context)
{
Requires.NotNull(context, nameof(context));
// This tells the database to close all connections and rolback open transactions.
// The intent to avoid any open database connections errors during database drop.
if (context.Database.Exists())
{
context.Database.ExecuteSqlCommand(
TransactionalBehavior.DoNotEnsureTransaction,
$"ALTER DATABASE [{context.Database.Connection.Database}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
}
base.InitializeDatabase(context);
}
}
}
using Migrations;
using System.Data.Entity;
using Validation;
namespace DatabaseInitializers
{
/// <summary>
/// If no database is created at startup, it will create one and perform a once time seed.
/// If there is already one created, it will update its schema according to the current state of the <see cref="DbContext"/>'s
/// models without dropping it, which means that it will retain previous data, without adding new one.
/// If this is used on an empty database, the deployed application will have an updated schema but without any data.
/// </summary>
/// <typeparam name="TContext"></typeparam>
/// <typeparam name="TConfig"></typeparam>
/// <remarks>
/// IMPORTANT: To use this option, your app's <see cref="DbContext"/>'s Configuration must be set to AutomaticMigrationsEnabled = true.
/// If you don't set this, EF's Code First will try to use the migrations you've created, which will not necessarily
/// match with the migrations already applied to the existing database and an error will occur when EF try to access/update it.
/// </remarks>
public sealed class MigrateDatabaseToLatestVersionAndSeedOnce : MigrateDatabaseToLatestVersion<MyDbContext, Configuration>
{
public MigrateDatabaseToLatestVersionAndSeedOnce()
{
}
public MigrateDatabaseToLatestVersionAndSeedOnce(string connectionStringName)
: base(connectionStringName)
{
}
public override void InitializeDatabase(MyDbContext context)
{
Requires.NotNull(context, nameof(context));
bool existed = context.Database.Exists();
base.InitializeDatabase(context);
if (!existed)
{
OneTimeSeed(context);
}
}
/// <summary>
/// This Seed method will run after initialization only if the database is not created on application startup.
/// It is used to inject data necessary for production into the database (like Module info or User accounts).
/// </summary>
/// <param name="context"></param>
private void OneTimeSeed(MyDbContext context)
{
// Seed here...
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment