MVC数据初始化
1.创建初始化方法
public class DbInitializer : CreateDatabaseIfNotExists<DbContext>
{
protected override void Seed(DbContext context)
{
Administrator ad = new Administrator()
{
Name = "系统管理员",
Sex = EnumSex.男,
Role = 1,
Creator = "XXC",
CreateTime = new DateTime(2017,2,21)
};
context.Administrators.Add(ad);
context.SaveChanges();
}
}
可用DropCreateDatabaseIfModelChanges(修改的时候删除原数据库)或者DropCreateDatabaseAlways(每次都删除原数据库)
2.在Global.asax使用初始化方法
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
DAL.DbContext dbContext = new DAL.DbContext();
Database.SetInitializer(new DAL.DbInitializer());
dbContext.Database.Initialize(true);
}