Beispiel #1
0
 public ShardingDbCreater()
 {
     //_srvComponent = service;
     _dbConfig = ShardingDbContext.GetDbConfig(typeof(T)) as ShardingDbTypeDefine <T>;
     if (_dbConfig == null)
     {
         throw new Exception($"未获取到{typeof(T).FullName}配置,请检查是否调用RegDb<T>进行注册!");
     }
 }
        private static readonly Dictionary <string, ShardingDbConfig> DbTypeConfigs = new Dictionary <string, ShardingDbConfig>(); //派生DbContext的配置信息

        /// <summary>
        /// 注册Db类型,并设置Db类型信息(设置后可使用ShardingDbCreater)
        /// </summary>
        protected static void RegDb <T>(ShardScopeType scopeType, Func <ContextScope, T> funCreate, Func <ContextScope, DbTransactionContext, T> createInTran = null)
            where T : ShardingDbContext
        {
            //add new config
            var dbType = typeof(T);
            var conf   = new ShardingDbTypeDefine <T>(scopeType)
            {
                DbConstructor = new ShardDbConstructor <T>
                {
                    NewDb       = funCreate,
                    NewDbInTran = createInTran
                }
            };

            DbTypeConfigs.Add(dbType.Name, conf);

            #region Reflect table entity

            var dbSetType = typeof(DbSet <>);
            foreach (var prop in dbType.GetProperties())
            {
                var propType = prop.PropertyType;
                if (!propType.IsGenericType || propType.GetGenericTypeDefinition() != dbSetType)
                {
                    continue;
                }

                var entType  = propType.GetGenericArguments()[0];
                var shardAtt = entType.GetCustomAttribute <ShardingTableAttribute>();
                if (shardAtt == null)
                {
                    continue;
                }

                //分表的Entity
                conf.ShardEntitys.Add(new EntityTypeSet
                {
                    EntityType    = entType,
                    TableBaseName = shardAtt.Name
                });
            }

            #endregion
        }