/// <summary>
    /// 说明:
    /// 创建日期:2016/9/30 14:49:48
    /// 创建人:曹永承
    /// </summary>
    public class AppDbContext:DbContext
    {
        private AppDbContext() : base("db")
        {
            Database.SetInitializer<AppDbContext>(new AppDbInit());
        }

        /// <summary>
        /// 创建唯一的AppDbContext
        /// </summary>
        /// <returns></returns>
        public static AppDbContext CreateOnly()
        {
            AppDbContext dbContext = CallContext.GetData("dbContext") as AppDbContext;
            if (dbContext == null)
            {
                dbContext = new AppDbContext();
                CallContext.SetData("dbContext", dbContext);
            }
            return dbContext;
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove(
                new PluralizingTableNameConvention());  //移除在数据库中表名复数约束
            base.OnModelCreating(modelBuilder);
        }

        public DbSet<AccountDetial> AccountDetails { get; set; }
    }

    public class AppDbInit : DropCreateDatabaseIfModelChanges<AppDbContext>
    {
        protected override void Seed(AppDbContext context)
        {
            init(context);
            base.Seed(context);
        }

        protected void init(AppDbContext context)
        {
            var list = new List<AccountDetial>
            {
                new AccountDetial {  Account="a",Age=27, Password="123456"},
                new AccountDetial {  Account="b",Age=26, Password="123456"},
                new AccountDetial {  Account="c",Age=2, Password="123456"},
                new AccountDetial {  Account="d",Age=24, Password="123456"},
                new AccountDetial {  Account="e",Age=50, Password="123456"}
            };

            foreach (AccountDetial account in list)
            {
                context.AccountDetails.Add(account);
            }
            context.SaveChanges();
        }
    }

 

 posted on 2016-09-30 16:35  Just_Do  阅读(1982)  评论(0编辑  收藏  举报