SELECT * into [backup_db].[dbo].[migrations]
FROM original_db.dbo.__MigrationHistory
after error
insert into original.dbo.__MigrationHistory
select * from [backup_db].[dbo].[migrations]
Showing posts with label EntityFramework. Show all posts
Showing posts with label EntityFramework. Show all posts
Wednesday, December 28, 2016
how to use EntityFramework in WinForms application beginning
/*WinForms application, EntityFramework ашиглах жишээ*/
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Database.SetInitializer<DbContextCurrentAssets>(new DbContextCurrentAssetsInitializer());
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.SetCompatibleTextRenderingDefault(false);
DevExpress.Skins.SkinManager.EnableMdiFormSkins();
DevExpress.Skins.SkinManager.EnableFormSkins();
DevExpress.UserSkins.BonusSkins.Register();
UserLookAndFeel.Default.SetSkinStyle("DevExpress Style");//Money Twins//DevExpress Style
DevExpress.Skins.SkinManager.EnableFormSkins();
DevExpress.UserSkins.BonusSkins.Register();
UserLookAndFeel.Default.SetSkinStyle("DevExpress Style");//Money Twins//DevExpress Style
Application.Run(new frmLogin());
}
}
}
}
/*********************************************************************************************************************************/
namespace HO.CURRENT.ASSETS
{
/// <summary>
/// DbContextCurrentAssets -г үүсгэсний дараа Seed дуудагдаж өгөгдөл дээрх анхны утгыг оруулах
/// боломжтой болох ба DropCreateDatabaseIfModelChanges шалтгаалж дахин програмд дуудагдахгүй.
/// </summary>
public class DbContextCurrentAssetsInitializer : DropCreateDatabaseIfModelChanges<DbContextCurrentAssets>
{
protected override void Seed(DbContextCurrentAssets context)
{
base.Seed(context);
namespace HO.CURRENT.ASSETS
{
/// <summary>
/// DbContextCurrentAssets -г үүсгэсний дараа Seed дуудагдаж өгөгдөл дээрх анхны утгыг оруулах
/// боломжтой болох ба DropCreateDatabaseIfModelChanges шалтгаалж дахин програмд дуудагдахгүй.
/// </summary>
public class DbContextCurrentAssetsInitializer : DropCreateDatabaseIfModelChanges<DbContextCurrentAssets>
{
protected override void Seed(DbContextCurrentAssets context)
{
base.Seed(context);
DbDefaultData.Initializer(context);
}
}
/// <summary>
/// DbHelper = new DbHelper<DbContextCurrentAssets>(serverName);
/// int ret = DbHelper.list<UserInfo>().Count();
/// Үед хамгийн түрүүнд дуудагдах ба DropCreateDatabaseIfModelChanges ямар байхаас шалтгаална.
/// </summary>
public class DbContextCurrentAssets : DbContext
{
public DbContextCurrentAssets()
: base(AppConfig.GetConnectionString("."))
{
}
}
}
/// <summary>
/// DbHelper = new DbHelper<DbContextCurrentAssets>(serverName);
/// int ret = DbHelper.list<UserInfo>().Count();
/// Үед хамгийн түрүүнд дуудагдах ба DropCreateDatabaseIfModelChanges ямар байхаас шалтгаална.
/// </summary>
public class DbContextCurrentAssets : DbContext
{
public DbContextCurrentAssets()
: base(AppConfig.GetConnectionString("."))
{
}
public DbContextCurrentAssets(string connStr)
: base(connStr)
{
}
: base(connStr)
{
}
/// <summary>
/// TContext db = instance();
/// DbSet sets = db.Set(typeof(TEntity));
/// IQueryable<TEntity> list = sets.OfType<TEntity>();
/// Үед байнга дуудагдаж ажиллана.
/// </summary>
/// <param name="modelBuilder"></param>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//base.OnModelCreating(modelBuilder);
//modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
//modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
//modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
/// TContext db = instance();
/// DbSet sets = db.Set(typeof(TEntity));
/// IQueryable<TEntity> list = sets.OfType<TEntity>();
/// Үед байнга дуудагдаж ажиллана.
/// </summary>
/// <param name="modelBuilder"></param>
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<>));
.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);
}
{
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());
//modelBuilder.Configurations.Add(new UserMap());
//modelBuilder.Configurations.Add(new RoleMap());
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
}
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<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<RoleInfo> RoleInfoes { get; set; }
public DbSet<UserRoleInfo> UserRoleInfoes { get; set; }
public DbSet<RoleWindowInfo> RoleWindowInfoes { get; set; }
..........................
..........................
}
}
/****************************************************************************************************/
хэрэв connStr ээ өөрсдөө нууцлан (_ConnectionString дэх user, pass аа нууц файлаас авч) generate ( учир нь апп програм аль ч ком дээр суух учир db,user,pass аа нууцлах шаардлагатай ) хийх бол нэг иймэрхүү функц ашиглаж болно.!
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;
}
}
{
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;
}
}
<connectionStrings>
<add name="DbContextCurrentAssets" connectionString="Data Source={0};Initial Catalog=DbCurrentAssets;User ID={1};Password={2};MultipleActiveResultSets=True;Pooling=false" providerName="System.Data.SqlClient" />
</connectionStrings>
<add name="DbContextCurrentAssets" connectionString="Data Source={0};Initial Catalog=DbCurrentAssets;User ID={1};Password={2};MultipleActiveResultSets=True;Pooling=false" providerName="System.Data.SqlClient" />
</connectionStrings>
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;
}
}
}
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;
}
}
}
Saturday, August 9, 2014
how to migrate database using entity framework when c# application runtime
PM> enable-migrations -Force
Checking if the context targets an existing database...
Detected database created with a database initializer. Scaffolded migration '201407300507349_InitialCreate' corresponding to existing database. To use an automatic migration instead, delete the Migrations folder and re-run Enable-Migrations specifying the -EnableAutomaticMigrations parameter.
Code First Migrations enabled for project HO.DIRECTORY.GUIDE.
1.
public sealed class Configuration : DbMigrationsConfiguration<HO.DIRECTORY.GUIDE.DbContextDirectoryGuide>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
ContextKey = "HO.DIRECTORY.GUIDE.DbContextDirectoryGuide";
}
2.
/// <summary>
/// програм ажиллаж байх явцад тохиолдсон асуудлуудыг тэмдэглэж үлдээнэ
/// </summary>
public class NotationInfo : NamedMetaData
{
}
3.
public DbSet<NotationInfo> NotationInfoes { get; set; }
4.
/// <summary>
/// Өгөгдлийн санд өөрчлөлт хийх үед энэ кодыг ашиглана
/// </summary>
public class DbInitializer : MigrateDatabaseToLatestVersion<DbContextDirectoryGuide, Migrations.Configuration>
{
}
5.
Database.SetInitializer(new DbInitializer());
//Database.SetInitializer<DbContextDirectoryGuide>(new DbContextDirectoryGuideInitializer());
PM> Add-Migration NotationInfoes
Scaffolding migration 'NotationInfoes'.
The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration NotationInfoes' again.
PM>
RUN Application then automatically change database without drop or create
Checking if the context targets an existing database...
Detected database created with a database initializer. Scaffolded migration '201407300507349_InitialCreate' corresponding to existing database. To use an automatic migration instead, delete the Migrations folder and re-run Enable-Migrations specifying the -EnableAutomaticMigrations parameter.
Code First Migrations enabled for project HO.DIRECTORY.GUIDE.
1.
public sealed class Configuration : DbMigrationsConfiguration<HO.DIRECTORY.GUIDE.DbContextDirectoryGuide>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
ContextKey = "HO.DIRECTORY.GUIDE.DbContextDirectoryGuide";
}
2.
/// <summary>
/// програм ажиллаж байх явцад тохиолдсон асуудлуудыг тэмдэглэж үлдээнэ
/// </summary>
public class NotationInfo : NamedMetaData
{
}
3.
public DbSet<NotationInfo> NotationInfoes { get; set; }
4.
/// <summary>
/// Өгөгдлийн санд өөрчлөлт хийх үед энэ кодыг ашиглана
/// </summary>
public class DbInitializer : MigrateDatabaseToLatestVersion<DbContextDirectoryGuide, Migrations.Configuration>
{
}
5.
Database.SetInitializer(new DbInitializer());
//Database.SetInitializer<DbContextDirectoryGuide>(new DbContextDirectoryGuideInitializer());
PM> Add-Migration NotationInfoes
Scaffolding migration 'NotationInfoes'.
The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration NotationInfoes' again.
PM>
RUN Application then automatically change database without drop or create
Subscribe to:
Posts (Atom)