0

I'm using Entity Framework with code first migrations. I want to seed my database after creation(I'm using creatIfNotExist). Is it possible to combine migrations with initializer that inherit from creatIfNotExist?

my code:

 static class Program
 {
   static void Main()
   {

     using (var db = new myDbContext())
     {
       db.Database.CreateIfNotExists();
     }
   }
}

  public sealed class Configuration : DbMigrationsConfiguration<Core.Models.SpanTesterContainer>
  {


    public Configuration()
    {
    AutomaticMigrationsEnabled = true;

    }

    protected override void Seed(Core.Models.SpanTesterContainer context){}
  } 


  public partial class myDbContext : DbContext
  {
    static SpanTesterContainer()
    {
      Database.SetInitializer<myDbContext>(new myDBInitializer());
    }

    public myDbContext()
    : base("Data Source=" +
           Properties.Settings.Default.ServerName + ";Initial Catalog=" +
           Properties.Settings.Default.DbName + ";Integrated Security=True;MultipleActiveResultSets=True")
    {
   }


public class SpanTesterDBInitializer : CreateDatabaseIfNotExists<SpanTesterContainer>
    {
        protected override void Seed(SpanTesterContainer context)
        {
           //Seed code here.
        }
  • Initializers that create the database are really only good for early prototyping because at some point you are probably not going to want to lose the non-seeded data. At that point, switch to a migration initializer and use a migration strategy to keep your databases in sync. http://blog.oneunicorn.com/2013/05/28/database-initializer-and-migrations-seed-methods/ – Steve Greene Jan 26 '16 at 17:09
  • Ok, but is there a way to mix them together? To use migrations and in the first use to seed the database? – Barak Ganon Jan 27 '16 at 07:23
  • Out of the box you can't mix them. You could write your own custom initializer. See https://entityframework.codeplex.com/workitem/1709 – Steve Greene Jan 27 '16 at 19:54

0 Answers0