I'm having trouble understanding the rules around when SeedData is called in EF Code First. Specifically, does it have anything to do with migrations? Migrations has it's own place to seed that seems different from the datacontext. I'm showing two examples below and I'm not sure which one is correct to use.
My Main Question: If I have a Migration, does the seeddata method not get called in my MultiTenantContext class? I have examples where it does and it does not and I can't figure out why.
In Migrations configuration.cs:
namespace WebApp.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<WebApp.Models.MultiTenantContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
ContextKey = "WebApp.Models.MultiTenantContext";
}
protected override void Seed(WebApp.Models.MultiTenantContext context)
{
var tenants = new List<Tenant>
{...};
tenants.ForEach(a => context.Tenants.Add(a));
context.SaveChanges();
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}
}
And in context class directly:
[DbConfigurationType(typeof(DataConfiguration))]
public class MultiTenantContext : DbContext
{
public DbSet<Tenant> Tenants { get; set; }
}
public class DataConfiguration : DbConfiguration
{
public DataConfiguration()
{
SetDatabaseInitializer(new MultiTenantContextInitializer());
}
}
public class MultiTenantContextInitializer :
CreateDatabaseIfNotExists<MultiTenantContext>
{
protected override void Seed(MultiTenantContext context)
{
var tenants = new List<Tenant>
{...}
tenants.ForEach(a => context.Tenants.Add(a));
context.SaveChanges();
}
}