Reputation: 511
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.
Upvotes: 3
Views: 298
Reputation: 9621
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
}
Upvotes: 1