Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 448
David Avatar asked Sep 23 '26 00:09

David


2 Answers

I know this is a bit late but I came across this answer and was unsatisfied with it. After a bit of tinkering here's a alternative solution.

Run the following commands:

add-migration YourSchemaMigration
update-database
add-migration YourDataMigration

This should scaffold and apply your schema changes, then the second add-migration call should scaffold an empty migration for you. Instead of using the migration to add or remove fields or tables, open up a DbContext in there and start dropping data

public partial class YourDataMigration : DbMigration 
{
    public override void Up() 
    {
        // Importing from CSV
        using(db = new FooDbContext())
            ImportUtil.ImportFoos(db, "initial_foo_data.csv"));
    }

    public override void Down()
    {
        // Nothing!
    }

}
like image 77
WhiteleyJ Avatar answered Sep 24 '26 13:09

WhiteleyJ


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();
    }
}
like image 44
Anthony Chu Avatar answered Sep 24 '26 13:09

Anthony Chu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!