Wednesday, December 28, 2016

maybe backup entity framework migration history manual

SELECT * into [backup_db].[dbo].[migrations]
  FROM original_db.dbo.__MigrationHistory

after error

  insert into original.dbo.__MigrationHistory
  select * from [backup_db].[dbo].[migrations]

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);
DevExpress.Skins.SkinManager.EnableMdiFormSkins();
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);
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("."))
{
}
public DbContextCurrentAssets(string 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>();
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<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; }
..........................
..........................
}
}

/****************************************************************************************************/


хэрэв 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;
}
}



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

Devexpress show ContextMenu in GridView Item

ContextMenuStrip cms = new ContextMenuStrip();
            ToolStripItem tsi = new ToolStripMenuItem("Мэдээлэл", null, (s, e) =>
            {
                if (DataModel != null)
                {
                    GridItemMetaInfo f = new GridItemMetaInfo(DataModel);
                    f.Show();
                }
            });
            cms.Items.Add(tsi);
            GridItemContextMenu = cms;

/*GridView*/


private void Grd_PopupMenuShowing(object sender, PopupMenuShowingEventArgs e)
        {
            showGridItemContextMenu((GridView)sender);
        }

        private void showGridItemContextMenu(GridView view)
        {
            if (view.FocusedColumn == null) return;

            int ri = view.FocusedRowHandle;
            int vi = view.FocusedColumn.VisibleIndex;
            GridViewInfo info = (GridViewInfo)view.GetViewInfo();

            GridCellInfo cell = info.GetGridCellInfo(ri, view.FocusedColumn);
            System.Drawing.Rectangle r = cell.Bounds;

            System.Drawing.Point point = new System.Drawing.Point(r.X + r.Width, r.Y + r.Height);
            GridItemContextMenu.Show(view.GridControl, point);
        }

        private void showGridItemContextMenu(GridView view, System.Drawing.Point location)
        {
            GridHitInfo hitInfo = view.CalcHitInfo(location);
            if (hitInfo.InRow)
            {
                view.FocusedRowHandle = hitInfo.RowHandle;
                GridItemContextMenu.Show(view.GridControl, location);
            }
        }