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.
-
Database First is when you already have the database and you would like to use it for creating your model. In this scenario you most likely have the data in the database. You also don't want/can't drop the database. I wonder what is the scenario where you want to seed the database if you already have data. Anyways - you can add data using a sql script or just by creating a context, creating entities adding them to context and saving changes. Since you don't delete the database you probably want to do this only once.Pawel– Pawel2013-05-11 04:55:50 +00:00Commented May 11, 2013 at 4:55
-
In db first database creation/seeding can be done in any way you like. EF is a complete outsider there.Gert Arnold– Gert Arnold2013-05-11 10:16:27 +00:00Commented May 11, 2013 at 10:16
1 Answer
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
}
}