Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityFramework Migrations - Seeding per Build Configuration

I am using EntityFramework 5 with Code First Migrations. What I want to be able to do is specify different Seed data depending on the Build Configuration. For example:

protected override void Seed(EFDbContext context)
{
    // This will be run in every Build configuration
    context.Table1.AddOrUpdate(new Table1 { Field1 = "Foo", Field2 = "Bar" });

    #if DEBUG
    // This will only be executed if we are Debuging
    context.Table1.AddOrUpdate(new Table1 { Field1 = "Blah", Field2 = "De Blah" });
    context.Table2.AddOrUpdate(new Table2 { Field1 = "Development Only" });
}

I know the code is probably wrong, I can figure out the correct method call once I know the best route to take for doing this.

Does EF have any built in method I have missed for doing this kind of thing?

Thanks

UPDATE

The code I used in the end was:

protected override void Seed(EFDbContext context)
{
    // This will be run in every Build configuration
    context.Table1.AddOrUpdate(t = t.Field1, new Table1 { Field1 = "Foo", Field2 = "Bar" });

    #if DEBUG
        // This will only be executed if we are Debuging
        context.Table1.AddOrUpdate(t = t.Field2, new Table1 { Field1 = "Blah", Field2 = "De Blah" });
        context.Table2.AddOrUpdate(t = t.Field1, new Table2 { Field1 = "Development Only" });
    #endif
}

It was as Yannick said, but in the AddOrUpdate method, you need to pass in the field that EF will use to establish if it is a new entry. Not part of my question, but thought I should provide the correct method for future reference.

like image 587
Dave Kirk Avatar asked Sep 03 '26 09:09

Dave Kirk


1 Answers

I think you already have the correct code (except the #endif statement).

This will work as you expect it:

protected override void Seed(EFDbContext context)
{
    // This will be executed in every Build configuration
    context.Table1.AddOrUpdate(new Table1 { Field1 = "Foo", Field2 = "Bar" });

    #if DEBUG
        // This will only be executed if DEBUG is defined, hence when you are debugging
        context.Table1.AddOrUpdate(new Table1 { Field1 = "Blah", Field2 = "De Blah" });
        context.Table2.AddOrUpdate(new Table2 { Field1 = "Development Only" });
    #endif
}
like image 170
Yannick Blondeau Avatar answered Sep 05 '26 22:09

Yannick Blondeau



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!