Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you seed data with Entity Framework Database First approach?

I see many examples of seeding with Code First, but I'm not sure I understand what the idiomatic way of seeding the database when using EF Database First.

like image 548
brushleaf Avatar asked May 10 '13 23:05

brushleaf


1 Answers

Best practice is very situation dependent. Then there is the DEV versus PROD environments. Auto seed when using Drop and recreate on model change during DEV so you have test data makes the most sense. This is when it used most.

Of cause you can a have a test method that you trigger manually. I personally find the idea an automatically triggered seed method not that exciting and more for DEV prototyping when the DB structure is volatile. When using migrations, you tend to keep your hard earned test data. Some use Seeding during initial installation in PROD. Others will have a specific load routines triggered during the installation/commissioning process. I like to use custom load routines instead.

EDIT: A CODE FIRST SAMPLE. With DB First you just write to the Db normally.

// select the appropriate initializer for your situation eg
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDbContext, MyMigrationConfiguration>());
Context.Database.Initialize(true);  // yes now please
//...
 public class MyMigrationConfiguration<TContext> : DbMigrationsConfiguration<TContext> 
    where TContext  : DbContext{

    public  MyMigrationConfiguration() {
        AutomaticMigrationsEnabled = true;  //fyi  options
        AutomaticMigrationDataLossAllowed = true; //fyi options
   }
    public override void Seed(TContext context)
    {
        base.Seed(context);
// SEED AWAY..... you have the context
    }

}
like image 92
phil soady Avatar answered Oct 12 '22 00:10

phil soady