zoukankan      html  css  js  c++  java
  • 创建单例的DbContext

     /// <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();
            }
        }
  • 相关阅读:
    jQuery火箭图标返回顶部代码
    类库引用EF
    Html.DropDownList
    MVC validation
    MVC @functions
    MVC 扩展方法特点
    Class 实现IDisposing方法
    MVC两个必懂核心
    Asp.net 服务器Application,Session,Cookie,ViewState和Cache区别
    sqlserver log
  • 原文地址:https://www.cnblogs.com/caoyc/p/5924205.html
Copyright © 2011-2022 走看看