Code First 数据库初始化
Global.asax
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); Database.SetInitializer<StarObjectContext>(new StarInitializer()); }
StarInitializer
View Code
using System.Data.Entity; using Star.Core.Models; namespace Star.Core.Data { public class StarInitializer : DropCreateDatabaseIfModelChanges<StarObjectContext> { protected override void Seed(StarObjectContext context) { //base.Seed(context); Account admin = new Account{ Email = "admin@**.cn", Password = "...", Permission = "admin", Stutas = AccountStutas.Enable, LastLoginTime = DateTime.Now, CreateTime = DateTime.Now }; context.Accounts.Add(admin); List<Category> categorys = new List<Category> { new Category{ Name = "category1", ShowOnHomepage = true }, new Category{ Name = "category2", ShowOnHomepage = true } }; categorys.ForEach(d => context.Categorys.Add(d)); context.SaveChanges(); } } }
StarObjectContext
public class StarObjectContext : DbContext//, IDbContext { public StarObjectContext(string nameOrConnectionString) : base(nameOrConnectionString) { //((IObjectContextAdapter) this).ObjectContext.ContextOptions.LazyLoadingEnabled = true; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Account>().ToTable("Account"); modelBuilder.Entity<Category>().ToTable("Category"); base.OnModelCreating(modelBuilder); } public DbSet<Account> Accounts { get; set; } public DbSet<Category> Categorys { get; set; } }
签名:删除冗余的代码最开心,找不到删除的代码最痛苦!