Thursday, August 14, 2014

how to make app db context using entity framework with migrations

program

public static DbHelper<DbContextDirectoryGuide> Helper { get; set; }

        private static bool IsInit = false;

        public static void Init()
        {
            var securityPassword = Controller.Current.BeginSettings["Setting_SecurityPassword"].ToString();
            AppConfig.SecurityPassword = Convert.ToBoolean(securityPassword);

            if (IsInit) return;
            IsInit = true;

            if (Database.Exists(Db.GetConnectionString()))
                Database.SetInitializer(new DbInitializer());
            else
                Database.SetInitializer<DbContextDirectoryGuide>(new DbContextDirectoryGuideInitializer());
        }


dbcontext

/// <summary>
    /// Энэ кодыг системийн админаас зөвшөөрөл авч байж өөрчилнө үү!
    /// </summary>
    public class DbContextDirectoryGuideInitializer : DropCreateDatabaseIfModelChanges<DbContextDirectoryGuide>
    {
        public override void InitializeDatabase(DbContextDirectoryGuide context)
        {
            base.InitializeDatabase(context);
        }

        protected override void Seed(DbContextDirectoryGuide context)
        {
            base.Seed(context);

            DbDefaultData.Initializer(context);
        }
    }

    /// <summary>
    /// Өгөгдлийн санд өөрчлөлт хийх үед энэ кодыг ашиглана
    /// </summary>
    public class DbInitializer : MigrateDatabaseToLatestVersion<DbContextDirectoryGuide, Migrations.Configuration>
    {
        public override void InitializeDatabase(DbContextDirectoryGuide context)
        {
            base.InitializeDatabase(context);
        }
    }

    public class DbContextDirectoryGuide : DbContext
    {
        public DbContextDirectoryGuide()
            : this(Db.GetConnectionString())
        {
        }

        public DbContextDirectoryGuide(string connString)
            : base(connString)
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //base.OnModelCreating(modelBuilder);
            //modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            //modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
            //modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

            var typesToRegister = Assembly.GetExecutingAssembly().GetTypes()
                .Where(type => !String.IsNullOrEmpty(type.Namespace))
                .Where(type => type.BaseType != null
                    && type.BaseType.IsGenericType
                    && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));

            foreach (var type in typesToRegister)
            {
                dynamic configurationInstance = Activator.CreateInstance(type);
                modelBuilder.Configurations.Add(configurationInstance);
            }

            //...or do it manually below. For example,
            //modelBuilder.Configurations.Add(new UserMap());
            //modelBuilder.Configurations.Add(new RoleMap());

            base.OnModelCreating(modelBuilder);

            modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
        }

        public DbSet<DeviceStreamInfo> DeviceStreamInfoes { get; set; }
       
        public DbSet<ExtendFieldInfo> ExtendFieldInfoes { get; set; }

        /// <summary>
        /// NotationInfoes is version 1.1.*.*
        /// </summary>
        public DbSet<NotationInfo> NotationInfoes { get; set; }
        public DbSet<SettingInfo> SettingInfoes { get; set; }

        public DbSet<OperatorCallInfo> OperatorCallInfoes { get; set; }

        public DbSet<EmployeeInfo> EmployeeInfoes { get; set; }

        public DbSet<AnswerConfigInfo> AnswerConfigInfoes { get; set; }
        public DbSet<ZarConfigInfo> ZarConfigInfoes { get; set; }
        public DbSet<MarketInfo> MarketInfoes { get; set; }
        public DbSet<MeetConfigInfo> MeetConfigInfoes { get; set; }

        public DbSet<CountryInfo> CountryInfoes { get; set; }
        public DbSet<CityInfo> CityInfoes { get; set; }
        public DbSet<SexInfo> SexInfoes { get; set; }
        public DbSet<UnitInfo> UnitInfoes { get; set; }

        public DbSet<UserInfo> UserInfoes { get; set; }
        public DbSet<RoleInfo> RoleInfoes { get; set; }
        public DbSet<UserRoleInfo> UserRoleInfoes { get; set; }
        public DbSet<RoleWindowInfo> RoleWindowInfoes { get; set; }

        public DbSet<CategoryInfo> CategoryInfoes { get; set; }
        public DbSet<TypeInfo> TypeInfoes { get; set; }

        public DbSet<CompanyInfo> CompanyInfoes { get; set; }
        public DbSet<ZarInfo> ZarInfoes { get; set; }
        public DbSet<ScheduleInfo> ScheduleInfoes { get; set; }
        public DbSet<PriceInfo> PriceInfoes { get; set; }
        public DbSet<MeetInfo> MeetInfoes { get; set; }
        public DbSet<OtherInfo> OtherInfoes { get; set; }
    }


lib

public class DbHelper<TContext> where TContext : DbContext
    {
        private string _ConnectionString;
        private TContext _ContextObject;
        private bool _UserAndRoleAndWindowAdded;

        public DbHelper(string serverName)
        {
            try
            {
                _ConnectionString = AppConfig.GetConnectionString(serverName);
                var conn = new System.Data.SqlClient.SqlConnection(_ConnectionString);
                conn.Open();
                conn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Та өгөгдлийн сангийн холболтоо шалгаад дахин оролдоод үзээрэй!\r\n\r\nАлдааны текст: " + ex.Message
                    , "Системийн Алдаа (DbHelper.Constractor)", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public bool reload(object entity)
        {
            try
            {
                TContext db = instance();
                DbEntityEntry entry = db.Entry(entity);
                entry.Reload();
                return true;
            }
            catch (Exception ex)
            {
                dispose();

                MessageBox.Show("Ачааллах үед алдаа гарлаа!\r\n\r\nАлдааны текст: " + ex.Message
                    , "Системийн Алдаа", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return false;
            }
        }

        public IQueryable<TEntity> list<TEntity>()
        {
            TContext db = instance();
            DbSet sets = db.Set(typeof(TEntity));
            IQueryable<TEntity> list = sets.OfType<TEntity>();
            return list;
        }

        public object addAndSave(object entity)
        {
            TContext db = instance();
            try
            {
                DbSet sets = db.Set(entity.GetType());
                object ret = sets.Add(entity);

                if (entity is IUserInfo || entity is IUserRoleInfo || entity is IRoleWindowInfo)
                {
                    _UserAndRoleAndWindowAdded = true;
                }

                db.SaveChanges();

                if (_UserAndRoleAndWindowAdded)
                {
                    AppSession.RefreshData();
                }

                return ret;
            }
            catch (Exception ex)
            {
                if (ex is DbEntityValidationException)
                {
                    foreach (DbEntityValidationResult result in ((DbEntityValidationException)ex).EntityValidationErrors)
                    {
                        if (result.Entry.State == EntityState.Added)
                        {
                            try
                            {
                                DbSet sets = db.Set(result.Entry.Entity.GetType());
                                object ret = sets.Remove(result.Entry.Entity);
                                if (ret != null) db.SaveChanges();
                            }
                            catch (Exception exm)
                            {
                                MessageBox.Show("Алдааны текст: " + exm.Message, "Алдаа", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        else if (result.Entry.State == EntityState.Modified)
                        {
                            try
                            {
                                result.Entry.Reload();
                            }
                            catch (Exception exm)
                            {
                                MessageBox.Show("Алдааны текст: " + exm.Message, "Алдаа", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                }
                else if (ex is DbUpdateException)
                {
                    MessageBox.Show("Алдааны текст: " + ex.Message, "Алдаа", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    //foreach (DbEntityEntry entity in ((DbUpdateException)ex).Entries)
                    //{
                    //    try
                    //    {
                    //        if (entity.State == EntityState.Modified)
                    //        {
                    //            entity.Reload();
                    //        }
                    //    }
                    //    catch (Exception exm)
                    //    {
                    //        MessageBox.Show("Алдааны текст: " + exm.Message, "Алдаа", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    //    }
                    //}
                }

                dispose();

                MessageBox.Show("Шинээр хадгалах үед алдаа гарлаа!\r\n\r\nАлдааны текст: " + ex.Message
                    , "Системийн Алдаа", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return null;
            }
            finally { _UserAndRoleAndWindowAdded = false; }
        }

        public bool add(object entity)
        {
            TContext db = instance();
            try
            {
                DbSet sets = db.Set(entity.GetType());
                object ret = sets.Add(entity);

                if (entity is IUserInfo || entity is IUserRoleInfo || entity is IRoleWindowInfo)
                {
                    _UserAndRoleAndWindowAdded = true;
                }

                return (ret != null);
            }
            catch (Exception ex)
            {
                dispose();

                MessageBox.Show("Нэмэх үед алдаа гарлаа!\r\n\r\nАлдааны текст: " + ex.Message
                    , "Системийн Алдаа", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return false;
            }
        }

        public bool remove(object entity)
        {
            TContext db = instance();
            DbEntityEntry entry = null;
            EntityState entryState = EntityState.Unchanged;
            try
            {
                entry = db.Entry(entity);
                entryState = entry.State;

                entry.State = EntityState.Deleted;
                int ret = db.SaveChanges();

                if (entity is IUserInfo || entity is IUserRoleInfo || entity is IRoleWindowInfo)
                {
                    AppSession.RefreshData();
                }

                return true;
            }
            catch (Exception ex)
            {
                if (entry != null)
                {
                    entry.State = entryState;
                }

                dispose();

                MessageBox.Show("Устгах үед алдаа гарлаа!\r\n\r\nАлдааны текст: " + ex.Message
                    , "Системийн Алдаа", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return false;
            }
        }

        public bool save()
        {
            TContext db = instance();
            try
            {
                int ret = db.SaveChanges();

                if (_UserAndRoleAndWindowAdded)
                {
                    AppSession.RefreshData();
                }

                return true;
            }
            catch (Exception ex)
            {
                if (ex is DbEntityValidationException)
                {
                    foreach (DbEntityValidationResult result in ((DbEntityValidationException)ex).EntityValidationErrors)
                    {
                        if (result.Entry.State == EntityState.Added)
                        {
                            try
                            {
                                DbSet sets = db.Set(result.Entry.Entity.GetType());
                                object ret = sets.Remove(result.Entry.Entity);
                                if (ret != null) db.SaveChanges();
                            }
                            catch (Exception exm)
                            {
                                MessageBox.Show("Алдааны текст: " + exm.Message, "Алдаа", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        else if (result.Entry.State == EntityState.Modified)
                        {
                            try
                            {
                                result.Entry.Reload();
                            }
                            catch (Exception exm)
                            {
                                MessageBox.Show("Алдааны текст: " + exm.Message, "Алдаа", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                }
                else if (ex is DbUpdateException)
                {
                    MessageBox.Show("Алдааны текст: " + ex.Message, "Алдаа", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    //foreach (DbEntityEntry entity in ((DbUpdateException)ex).Entries)
                    //{
                    //    try
                    //    {
                    //        if (entity.State == EntityState.Modified)
                    //        {
                    //            entity.Reload();
                    //        }
                    //    }
                    //    catch (Exception exm)
                    //    {
                    //        MessageBox.Show("Алдааны текст: " + exm.Message, "Алдаа", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    //    }
                    //}
                }

                dispose();

                MessageBox.Show("Хадгалах үед алдаа гарлаа!\r\n\r\nАлдааны текст: " + ex.Message
                    , "Системийн Алдаа", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return false;
            }
            finally { _UserAndRoleAndWindowAdded = false; }
        }

        private void dispose()
        {
            if (_ContextObject != null)
            {
                //_ContextObject.ChangeTracker.Entries().Single().
                //if (_ContextObject.Database.Connection.State != System.Data.ConnectionState.Closed)
                //{
                //    _ContextObject.Database.Connection.Close();
                //}

                //_ContextObject.Dispose();
                //_ContextObject = null;
            }
        }

        private TContext instance()
        {
            if (_ContextObject is DbContext)
            {
                return _ContextObject;
            }

            try
            {
                Type type = typeof(TContext);
                Assembly assembly = type.Assembly;

                ConstructorInfo[] ConstructorInformation = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public);

                object[] args = new object[] { _ConnectionString };

                _ContextObject = (TContext)assembly.CreateInstance(type.FullName, true
                    , BindingFlags.Instance | BindingFlags.Public
                    , null, args, System.Globalization.CultureInfo.CurrentCulture
                    , null);

                return _ContextObject;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Өгөгдлийн сангийн класс үүсгэх үед асуудал гарлаа!\r\n\r\nАлдааны текст: " + ex.Message
                    , "Системийн Алдаа (DbHelper.instance)", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return null;
            }
        }
    }

No comments: