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; }
    }

 

参考资料:http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx

posted @ 2012-12-19 10:58  Season2009  阅读(295)  评论(0编辑  收藏  举报