Skip to content

Instantly share code, notes, and snippets.

@DalSoft
Last active March 12, 2018 07:41
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save DalSoft/8684d8be9566221ca7b1b8e962db241f to your computer and use it in GitHub Desktop.
Save DalSoft/8684d8be9566221ca7b1b8e962db241f to your computer and use it in GitHub Desktop.
Entity Framework Core Migrations and Seeding
using System;
using System.IO;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.Extensions.Configuration;
namespace DalSoft.Data
{
public class DalSoftDbContext : DbContext
{
public DalSoftDbContext(DbContextOptions options) : base(options) { }
public DalSoftDbContext() /* Required for migrations */{ }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (optionsBuilder.IsConfigured) return;
//Called by parameterless ctor Usually Migrations
var environmentName = Environment.GetEnvironmentVariable("EnvironmentName") ?? "local";
optionsBuilder.UseSqlServer(
new ConfigurationBuilder()
.SetBasePath(Path.GetDirectoryName(GetType().GetTypeInfo().Assembly.Location))
.AddJsonFile($"appsettings.{environmentName}.json", optional: false, reloadOnChange: false)
.Build()
.GetConnectionString("DalSoftDbContext")
);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore.Migrations;
namespace DalSoft.Data.Migrations
{
/// <summary>Workaound for EF core not having Seed support https://github.com/aspnet/EntityFramework/issues/629 </summary>
public partial class ExampleSeedMigration : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
using (var db = new DalSoftDbContext())
{
db.Apps.AddRange(new MyEntities[] {...});
db.SaveChanges();
}
}
protected override void Down(MigrationBuilder migrationBuilder)
{
using (var db = new DalSoftDbContext())
{
db.RemoveRange(db.MyEntities)
db.SaveChanges();
}
}
}
}
using System;
using System.IO;
using Microsoft.AspNetCore.Hosting;
namespace DalSoft.Data
{
public class Program
{
public static void Main(string[] args)
{
Console.Write("This is the workaround for:" +
"Could not invoke this command on the startup project. " +
"This preview of Entity Framework tools does not support commands on class library projects in ASP.NET Core and " +
".NET Core applications. See http://go.microsoft.com/fwlink/?LinkId=798221 for details and workarounds.");
new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.Build();
}
}
}
{
"version": "1.0.0-*",
"buildOptions": {
"emitEntryPoint": true
},
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.1"
},
"Microsoft.Extensions.DependencyInjection": "1.0.0-*",
"Microsoft.Extensions.DependencyInjection.Abstractions": "1.0.0",
"Microsoft.Extensions.PlatformAbstractions": "1.0.0",
"Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
"Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
"Microsoft.Extensions.Configuration.Json": "1.0.0",
"Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
"Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
"Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.0"
},
"tools": {
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
},
"runtimes": {
"win10-x64": {}
},
"frameworks": {
"netcoreapp1.0": {
"imports": [
"dotnet5.6",
"portable-net45+win8"
]
}
}
}
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace DalSoft.Data
{
/// <summary>EF core mirgations at the moment expects a Web startup and if we don't bootstrap it like this the -environmentName switch never gets populated.
/// I had to read the source to see why it wasn't working https://github.com/aspnet/EntityFramework/commit/7f48d0c0fca054ed70bebe0e8d2c58ee3cc3df9b</summary>
public class Startup
{
private readonly IConfigurationRoot _configuration;
private readonly IHostingEnvironment _hostingEnvironment;
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false, reloadOnChange: false);
builder.AddEnvironmentVariables();
_configuration = builder.Build();
_hostingEnvironment = env;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DalSoftDbContext>(options =>
{
Environment.SetEnvironmentVariable("EnvironmentName", _hostingEnvironment.EnvironmentName.ToLower()== "development" ? "local" : _hostingEnvironment.EnvironmentName);
options.UseSqlServer(_configuration.GetConnectionString("DalSoftDbContext"));
});
}
public void Configure(IApplicationBuilder app)
{
}
}
}
@weitzhandler
Copy link

Is this intended to be used with EF 6.1.3 or only EF7?

@scavarda
Copy link

Pay attention:
MigrationBuilder methods in "protected override void Up(MigrationBuilder migrationBuilder)" will be executed in the end, while "db.saveChanges()" will be immediately executed.
My situation:
I have to create a new model and seed data for it, I can't do it in a single migration.
I have to apply the creation in a previous migration and then apply a next migration with seed data

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment