CreateDbContext() public method

创建DbContext(必须先注册实体到数据表的映射后才可创建DbContext)
public CreateDbContext ( ) : IDbContext
return IDbContext
Example #1
0
        public virtual IDatabaseSchema Load(DbConfiguration cfg)
        {
            var databaseSchema = new DatabaseSchema();

            ColumnInfo[] allColumns = null;
            ConstraintInfo[] allConstraints = null;
            ForeignKeyInfo[] allFks = null;
            using (var ctx = cfg.CreateDbContext())
            {
                InitConnection(ctx.Connection);
                using (var reader = ctx.DbHelper.ExecuteReader(AllColumnsSql))
                    allColumns = reader.ToList<ColumnInfo>().ToArray();
                using (var reader = ctx.DbHelper.ExecuteReader(AllConstraintsSql))
                    allConstraints = reader.ToList<ConstraintInfo>().ToArray();
                using (var reader = ctx.DbHelper.ExecuteReader(AllFKsSql))
                    allFks = reader.ToList<ForeignKeyInfo>().ToArray();
            }

            PopulateConstraints(allColumns, allConstraints);

            Dictionary<string, TableSchema> tables = new Dictionary<string, TableSchema>();
            PopulateTables(allColumns, tables);

            foreach (var item in allFks)
            {
                TableSchema thisTable = null;
                TableSchema otherTable = null;
                IColumnSchema thisKey = null;
                IColumnSchema otherKey = null;

                var key = string.Format("{0}.{1}", item.ThisSchema, item.ThisTableName);
                if (tables.TryGetValue(key, out thisTable))
                    thisKey = thisTable.AllColumns.FirstOrDefault(p => p.ColumnName == item.ThisKey);

                key = string.Format("{0}.{1}", item.OtherSchema, item.OtherTableName);
                if(tables.TryGetValue(key, out otherTable))
                    otherKey = otherTable.AllColumns.FirstOrDefault(p => p.ColumnName == item.OtherKey);

                thisTable.AddFK(new ForeignKeySchema
                {
                    ThisTable = thisTable
                    , Name = item.Name
                    , ThisKey = thisKey
                    , OtherTable = otherTable
                    , OtherKey = otherKey });

            }

            databaseSchema.Tables = tables.Values.Where(p => !p.IsView).ToArray();
            databaseSchema.Views = tables.Values.Where(p => p.IsView).ToArray();

            return databaseSchema;
        }