Search code examples
c#entity-frameworkef-code-firstcode-firstentity-framework-migrations

Entity Framework: Multiple code first migrations and the configuration seed method


I'm adding a column to a table with Entity Framework Code First Migrations. I've read you can use the Seed method in Configuration.cs and it will seed data when update-database is run. How does this work if you have multiple migrations? One migration might need to seed some data and another migration might need other data seeded. There is only one Seed method in the configuration file. How do you prevent Entity Framework from seeding the same data multiple times in the future when you add more migrations? Do you just delete the contents of the Seed method in the configuration file?


Solution

  • When Update-Database is run, the Seed method is passed the DbContext as the argument. You can do anything you'd like with the context, including querying the database to see what data is already there and making sure your Seed method is idempotent.

    For instance, you might want to always make sure the database is always seeded with an administrator if none exist...

    protected override void Seed(MyDbContext context)
    {
        if (!context.Users.Any(u => u.Username == "administrator"))
        {
            var user = new User { Username = "administrator", PasswordHash = "hashed password" };
            context.Users.Add(user);
            context.SaveChanges();
        }
    }