您創建一個自定義數據庫初始化,並覆蓋Seed
方法
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" });
//EF will call SaveChanges itself
}
}
然後你註冊這個初始化爲您導出的上下文MyContext
:
Database.SetInitializer<MyContext>(new MyContextInitializer());
這是Database
類的靜態方法應該在應用程序啓動時調用一次。你也可以把它放到你的上下文的靜態構造函數,以確保您創建的第一個上下文實例之前初始化器設置:
static MyContext()
{
Database.SetInitializer<MyContext>(new MyContextInitializer());
}
不是基初始化DropCreateDatabaseIfModelChanges<T>
您也可以從DropCreateDatabaseAlways<T>
或CreateDatabaseIfNotExists<T>
,如果得到的更好地滿足您的需求。