You create a custom database initializer and overwrite the Seed
method
public class MyContextInitializer : DropCreateDatabaseIfModelChanges<MyContext> { protected override void Seed(MyContext context) { context.ContactTypes.Add(new ContactType { DisplayName = "Home" }); context.ContactTypes.Add(new ContactType { DisplayName = "Mobile" }); context.ContactTypes.Add(new ContactType { DisplayName = "Office" }); context.ContactTypes.Add(new ContactType { DisplayName = "Fax" });
Then you register this initializer for your derived MyContext
context:
Database.SetInitializer<MyContext>(new MyContextInitializer());
This is a static method of the Database
class and should be called somewhere once at application startup. You can also put it in the static constructor of your context to make sure that the intializer is set before creating the first instance of the context:
static MyContext() { Database.SetInitializer<MyContext>(new MyContextInitializer()); }
Instead of the basic DropCreateDatabaseIfModelChanges<T>
initializer, you can also get from DropCreateDatabaseAlways<T>
or CreateDatabaseIfNotExists<T>
if that suits your needs better.
source share