publicoverridevoidCustomize(ModelBuilder modelBuilder, DbContext context) { base.Customize(modelBuilder, context); var dbContextBase = context as DbContextBase; var shardingTypeFinder = dbContextBase.ServiceProvider.GetService<IShardingTypeFinder>(); //查找需要重新映射表名的类 var shardingTypes = shardingTypeFinder.FindAll(true);
if (shardingTypes != null && shardingTypes.Count() > 0) {
if (context is DbContextBase contextBase) { if (!string.IsNullOrEmpty(contextBase.ShardingRule)) { foreach (var type in shardingTypes) { switch (contextBase.DbContextOptions.DatabaseType) { case DatabaseType.SqlServer: modelBuilder.Entity(type).ToTable($"{type.Name}_{contextBase.ShardingRule}"); break; case DatabaseType.Sqlite: modelBuilder.Entity(type).ToTable($"{type.Name}_{contextBase.ShardingRule}"); break; case DatabaseType.MySql: modelBuilder.Entity(type).ToTable($"{type.Name}_{contextBase.ShardingRule}".ToMySQLName()); break; case DatabaseType.Oracle: modelBuilder.Entity(type).ToTable($"{type.Name}_{contextBase.ShardingRule}".ToOracleName()); break; default: modelBuilder.Entity(type).ToTable($"{type.Name}_{contextBase.ShardingRule}"); break; } } } }
DbContextOptionsBuilder<DbContextBase> optionsBuilder = new DbContextOptionsBuilder<DbContextBase>(); optionsBuilder.UseSqlServer("connStr"); var options = optionsBuilder.Options; using (var dbContext = new DbContextBase("202209", options)) { //TODO.... }
DbContextOptionsBuilder<DbContextBase> optionsBuilder = new DbContextOptionsBuilder<DbContextBase>(); IDbConnection connection = new SqlConnection("connStr"); optionsBuilder.UseSqlServer(connection); var options = optionsBuilder.Options; using (var dbContext = new DbContextBase("202209", options)) { using (var transaction =await dbContext.Database.BeginTransactionAsync()) { using (var dbContext2 = new DbContextBase("202210", options)) {