Search code examples
entity-frameworkentity-framework-6

When is the Seed method called in a EF code first migrations scenario?


I'm new in a project and there is this class for the seed data:

 internal sealed class Configuration : DbMigrationsConfiguration<DAL.Context>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
        }

And this code to start the seed:

protected override void Seed(Context context)
    {
        try
        {

My question is: when is the Seed method called? Only when a user does update-database and the user doesn't have the database (basicly a new user), or also when the user with an existing database calls an update-database?


Solution

  • Seed method is used to have have some known static data like countries, states with initial database in code first. The Seed method will execute and populate these data every time the database is newly created.

    Other use case is to use during the development/testing phase where you often need to recreate the database and populate database tables with sample data.

    In other scenario if needs to add to that static data without dropping database(because it has real data) migrations Seed method used. Whenever you run the migration and update the database it will run the seed method. Needs to be careful here with long running Seed method as it runs every time the application starts.

    Please go through Database initializer and Migrations Seed methods for more explanation.