Merge pull request #171 from dodu2014/x.6.x-动态分库

升级 x.6.x 动态分库 示例
This commit is contained in:
xuejmnet 2022-07-13 08:53:38 +08:00 committed by GitHub
commit 26fe6d225c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
28 changed files with 489 additions and 1078 deletions

View File

@ -7,10 +7,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebApplication1", "WebAppli
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebApplication1.Data", "WebApplication1.Data\WebApplication1.Data.csproj", "{5C6E6694-6CBC-46BE-964E-608A8D97604F}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebApplication1.Migrations.NoSharding", "WebApplication1.Migrations.NoSharding\WebApplication1.Migrations.NoSharding.csproj", "{B6421961-3EF8-48FD-A291-32E1DF63141B}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebApplication1.Migrations.Tool", "WebApplication1.Migrations.Tool\WebApplication1.Migrations.Tool.csproj", "{212AA572-E710-447E-9F09-187B3B62D2BE}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebApplication1.Migrations.Sharding", "WebApplication1.Migrations.Sharding\WebApplication1.Migrations.Sharding.csproj", "{B6FDDE11-E2E7-43F7-AAC6-79865FB73928}"
EndProject
Global
@ -27,14 +23,6 @@ Global
{5C6E6694-6CBC-46BE-964E-608A8D97604F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5C6E6694-6CBC-46BE-964E-608A8D97604F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5C6E6694-6CBC-46BE-964E-608A8D97604F}.Release|Any CPU.Build.0 = Release|Any CPU
{B6421961-3EF8-48FD-A291-32E1DF63141B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B6421961-3EF8-48FD-A291-32E1DF63141B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B6421961-3EF8-48FD-A291-32E1DF63141B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B6421961-3EF8-48FD-A291-32E1DF63141B}.Release|Any CPU.Build.0 = Release|Any CPU
{212AA572-E710-447E-9F09-187B3B62D2BE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{212AA572-E710-447E-9F09-187B3B62D2BE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{212AA572-E710-447E-9F09-187B3B62D2BE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{212AA572-E710-447E-9F09-187B3B62D2BE}.Release|Any CPU.Build.0 = Release|Any CPU
{B6FDDE11-E2E7-43F7-AAC6-79865FB73928}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B6FDDE11-E2E7-43F7-AAC6-79865FB73928}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B6FDDE11-E2E7-43F7-AAC6-79865FB73928}.Release|Any CPU.ActiveCfg = Release|Any CPU

View File

@ -12,6 +12,7 @@ using ShardingCore.Core.VirtualDatabase.VirtualDataSources;
using ShardingCore.Core.VirtualRoutes.TableRoutes.RouteTails.Abstractions;
using ShardingCore.EFCores.OptionsExtensions;
using ShardingCore.Extensions;
using ShardingCore.Sharding;
using ShardingCore.Sharding.Abstractions;
using ShardingCore.Sharding.ShardingDbContextExecutors;
using WebApplication1.Data.Models;
@ -21,11 +22,12 @@ namespace WebApplication1.Data
public class AbstaractShardingDbContext : IdentityDbContext, IShardingDbContext, ISupportShardingReadWrite, IShardingTableDbContext
{
public AbstaractShardingDbContext([NotNull] DbContextOptions<AbstaractShardingDbContext> options) : base(options)
{
var wrapOptionsExtension = options.FindExtension<ShardingWrapOptionsExtension>();
if (wrapOptionsExtension != null)
_shardingDbContextExecutor = (IShardingDbContextExecutor)Activator.CreateInstance(typeof(ShardingDbContextExecutor<>).GetGenericType0(GetType()), this);
_shardingDbContextExecutor = new ShardingDbContextExecutor(this);
}
#region
@ -35,7 +37,7 @@ namespace WebApplication1.Data
/// <summary>
/// 是否是真正的执行者
/// </summary>
private bool isExecutor => _shardingDbContextExecutor == null;
private bool IsExecutor => _shardingDbContextExecutor == null;
/// <summary>
/// 读写分离优先级
@ -131,7 +133,7 @@ namespace WebApplication1.Data
/// <param name="routeTail"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public DbContext GetDbContext(string dataSourceName, bool parallelQuery, IRouteTail routeTail)
public DbContext GetDbContext(string dataSourceName, CreateDbContextStrategyEnum parallelQuery, IRouteTail routeTail)
{
var dbContext = _shardingDbContextExecutor.CreateDbContext(parallelQuery, dataSourceName, routeTail);
//if (!parallelQuery && dbContext is AbpDbContext<TDbContext> abpDbContext) {
@ -186,32 +188,32 @@ namespace WebApplication1.Data
public override EntityEntry Add(object entity)
{
if (isExecutor) base.Add(entity);
if (IsExecutor) base.Add(entity);
return CreateGenericDbContext(entity).Add(entity);
}
public override EntityEntry<TEntity> Add<TEntity>(TEntity entity)
{
if (isExecutor) return base.Add(entity);
if (IsExecutor) return base.Add(entity);
return CreateGenericDbContext(entity).Add(entity);
}
public override ValueTask<EntityEntry<TEntity>> AddAsync<TEntity>(TEntity entity, CancellationToken cancellationToken = new CancellationToken())
{
if (isExecutor) return base.AddAsync(entity, cancellationToken);
if (IsExecutor) return base.AddAsync(entity, cancellationToken);
return CreateGenericDbContext(entity).AddAsync(entity, cancellationToken);
}
public override ValueTask<EntityEntry> AddAsync(object entity, CancellationToken cancellationToken = new CancellationToken())
{
if (isExecutor) return base.AddAsync(entity, cancellationToken);
if (IsExecutor) return base.AddAsync(entity, cancellationToken);
return CreateGenericDbContext(entity).AddAsync(entity, cancellationToken);
}
public override void AddRange(params object[] entities)
{
if (isExecutor)
if (IsExecutor)
{
base.AddRange(entities);
return;
@ -234,7 +236,7 @@ namespace WebApplication1.Data
public override void AddRange(IEnumerable<object> entities)
{
if (isExecutor)
if (IsExecutor)
{
base.AddRange(entities);
return;
@ -257,7 +259,7 @@ namespace WebApplication1.Data
public override async Task AddRangeAsync(params object[] entities)
{
if (isExecutor)
if (IsExecutor)
{
await base.AddRangeAsync(entities);
return;
@ -280,7 +282,7 @@ namespace WebApplication1.Data
public override async Task AddRangeAsync(IEnumerable<object> entities, CancellationToken cancellationToken = new CancellationToken())
{
if (isExecutor)
if (IsExecutor)
{
await base.AddRangeAsync(entities, cancellationToken);
return;
@ -304,21 +306,21 @@ namespace WebApplication1.Data
public override EntityEntry<TEntity> Attach<TEntity>(TEntity entity)
{
if (isExecutor)
if (IsExecutor)
return base.Attach(entity);
return CreateGenericDbContext(entity).Attach(entity);
}
public override EntityEntry Attach(object entity)
{
if (isExecutor)
if (IsExecutor)
return base.Attach(entity);
return CreateGenericDbContext(entity).Attach(entity);
}
public override void AttachRange(params object[] entities)
{
if (isExecutor)
if (IsExecutor)
{
base.AttachRange(entities);
return;
@ -341,7 +343,7 @@ namespace WebApplication1.Data
public override void AttachRange(IEnumerable<object> entities)
{
if (isExecutor)
if (IsExecutor)
{
base.AttachRange(entities);
return;
@ -369,35 +371,35 @@ namespace WebApplication1.Data
public override EntityEntry<TEntity> Entry<TEntity>(TEntity entity)
{
if (isExecutor)
if (IsExecutor)
return base.Entry(entity);
return CreateGenericDbContext(entity).Entry(entity);
}
public override EntityEntry Entry(object entity)
{
if (isExecutor)
if (IsExecutor)
return base.Entry(entity);
return CreateGenericDbContext(entity).Entry(entity);
}
public override EntityEntry<TEntity> Update<TEntity>(TEntity entity)
{
if (isExecutor)
if (IsExecutor)
return base.Update(entity);
return CreateGenericDbContext(entity).Update(entity);
}
public override EntityEntry Update(object entity)
{
if (isExecutor)
if (IsExecutor)
return base.Update(entity);
return CreateGenericDbContext(entity).Update(entity);
}
public override void UpdateRange(params object[] entities)
{
if (isExecutor)
if (IsExecutor)
{
base.UpdateRange(entities);
return;
@ -420,7 +422,7 @@ namespace WebApplication1.Data
public override void UpdateRange(IEnumerable<object> entities)
{
if (isExecutor)
if (IsExecutor)
{
base.UpdateRange(entities);
return;
@ -443,21 +445,21 @@ namespace WebApplication1.Data
public override EntityEntry<TEntity> Remove<TEntity>(TEntity entity)
{
if (isExecutor)
if (IsExecutor)
return base.Remove(entity);
return CreateGenericDbContext(entity).Remove(entity);
}
public override EntityEntry Remove(object entity)
{
if (isExecutor)
if (IsExecutor)
return base.Remove(entity);
return CreateGenericDbContext(entity).Remove(entity);
}
public override void RemoveRange(params object[] entities)
{
if (isExecutor)
if (IsExecutor)
{
base.RemoveRange(entities);
return;
@ -480,7 +482,7 @@ namespace WebApplication1.Data
public override void RemoveRange(IEnumerable<object> entities)
{
if (isExecutor)
if (IsExecutor)
{
base.RemoveRange(entities);
return;
@ -504,13 +506,13 @@ namespace WebApplication1.Data
public override int SaveChanges()
{
if (isExecutor) return base.SaveChanges();
if (IsExecutor) return base.SaveChanges();
return this.SaveChanges(true);
}
public override int SaveChanges(bool acceptAllChangesOnSuccess)
{
if (isExecutor)
if (IsExecutor)
return base.SaveChanges(acceptAllChangesOnSuccess);
//ApplyShardingConcepts();
int i = 0;
@ -534,14 +536,14 @@ namespace WebApplication1.Data
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
{
if (isExecutor)
if (IsExecutor)
return base.SaveChangesAsync(cancellationToken);
return this.SaveChangesAsync(true, cancellationToken);
}
public override async Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = new CancellationToken())
{
if (isExecutor)
if (IsExecutor)
return await base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
//ApplyShardingConcepts();
int i = 0;
@ -567,7 +569,7 @@ namespace WebApplication1.Data
public override void Dispose()
{
if (isExecutor)
if (IsExecutor)
{
base.Dispose();
}
@ -580,7 +582,7 @@ namespace WebApplication1.Data
public override async ValueTask DisposeAsync()
{
if (isExecutor)
if (IsExecutor)
{
await base.DisposeAsync();
}
@ -613,6 +615,5 @@ namespace WebApplication1.Data
builder.Entity<TestModelKey>().HasKey(t => new { t.Id, t.Key });
builder.Entity<TestModelKey>().Property(o => o.Key).IsRequired().HasMaxLength(36);
}
}
}

View File

@ -1,4 +1,6 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using ShardingCore.Core.RuntimeContexts;
using ShardingCore.Helpers;
using System;
using System.Linq;
@ -19,7 +21,8 @@ namespace WebApplication1.Data.Extensions
using (var scope = serviceProvider.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<AbstaractShardingDbContext>();
db.Database.EnsureCreated();
var runtimeContext = scope.ServiceProvider.GetRequiredService<IShardingRuntimeContext>();
//db.Database.EnsureCreated();
var dblist = db.TestModelKeys.Select(m => m.Key).ToList();
// 存入到动态库配置文件缓存中
@ -28,8 +31,10 @@ namespace WebApplication1.Data.Extensions
// 遍历添加动态数据源
foreach (var key in dblist)
{
DynamicShardingHelper.DynamicAppendDataSource<AbstaractShardingDbContext>("c1", key, $"server=127.0.0.1;port=5432;uid=postgres;pwd=3#SanJing;database=shardingCoreDemo_{key};");
DynamicShardingHelper.DynamicAppendDataSourceOnly(runtimeContext, key, $"server=127.0.0.1;port=5432;uid=postgres;pwd=3#SanJing;database=shardingCoreDemo_{key};");
}
db.Database.Migrate();
}
return serviceProvider;

View File

@ -1,11 +1,19 @@
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace WebApplication1.Data.Models
{
public class TestModel
{
public Guid Id { get; set; } = Guid.NewGuid();
//[Key]
//[DatabaseGenerated(DatabaseGeneratedOption.None)]
//public Guid Id2 { get; set; } = Guid.NewGuid();
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Content { get; set; } = "";

View File

@ -7,7 +7,7 @@ namespace WebApplication1.Data.Sharding
public class GuidShardingTableVirtualTableRoute : AbstractSimpleShardingModKeyStringVirtualTableRoute<GuidShardingTable>
{
public GuidShardingTableVirtualTableRoute() : base(3, 6, '0')
public GuidShardingTableVirtualTableRoute() : base(3, 6)
{
}

View File

@ -7,7 +7,7 @@ namespace WebApplication1.Data.Sharding
public class StudentVirtualTableRoute : AbstractSimpleShardingModKeyStringVirtualTableRoute<Student>
{
public StudentVirtualTableRoute() : base(3, 6, '0')
public StudentVirtualTableRoute() : base(3, 6)
{
}

View File

@ -4,6 +4,7 @@ using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations.Operations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Infrastructure.Internal;
using Npgsql.EntityFrameworkCore.PostgreSQL.Migrations;
using ShardingCore.Core.RuntimeContexts;
using ShardingCore.Helpers;
using ShardingCore.Sharding.Abstractions;
using System.Linq;
@ -15,9 +16,11 @@ namespace WebApplication1.Data
/// </summary>
public class ShardingMigrationsSqlGenerator<TShardingDbContext> : NpgsqlMigrationsSqlGenerator where TShardingDbContext : DbContext, IShardingDbContext
{
private readonly IShardingRuntimeContext runtimeContext;
public ShardingMigrationsSqlGenerator(MigrationsSqlGeneratorDependencies dependencies, INpgsqlSingletonOptions npgsqlSingletonOptions) : base(dependencies, npgsqlSingletonOptions)
public ShardingMigrationsSqlGenerator(MigrationsSqlGeneratorDependencies dependencies, INpgsqlSingletonOptions npgsqlSingletonOptions, IShardingRuntimeContext runtimeContext) : base(dependencies, npgsqlSingletonOptions)
{
this.runtimeContext = runtimeContext;
}
protected override void Generate(MigrationOperation operation, IModel model, MigrationCommandListBuilder builder)
@ -27,7 +30,7 @@ namespace WebApplication1.Data
var newCmds = builder.GetCommandList().ToList();
var addCmds = newCmds.Where(x => !oldCmds.Contains(x)).ToList();
MigrationHelper.Generate<TShardingDbContext>(operation, builder, Dependencies.SqlGenerationHelper, addCmds);
MigrationHelper.Generate(runtimeContext, operation, builder, Dependencies.SqlGenerationHelper, addCmds);
}
}

View File

@ -7,7 +7,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="6.0.6" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="6.0.5" />
<PackageReference Include="ShardingCore" Version="6.5.0.11" />
<PackageReference Include="ShardingCore" Version="6.6.0.9" />
</ItemGroup>
</Project>

View File

@ -1,297 +0,0 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using WebApplication1.Data;
#nullable disable
namespace WebApplication1.Migrations.NoSharding.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20220610041036_initialCreate")]
partial class initialCreate
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "6.0.5")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("AspNetRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("AccessFailedCount")
.HasColumnType("integer");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("boolean");
b.Property<bool>("LockoutEnabled")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("timestamp with time zone");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.HasColumnType("text");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("boolean");
b.Property<string>("SecurityStamp")
.HasColumnType("text");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("boolean");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("AspNetUsers", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<string>("ProviderKey")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<string>("ProviderDisplayName")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("RoleId")
.HasColumnType("text");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("LoginProvider")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<string>("Name")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<string>("Value")
.HasColumnType("text");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens", (string)null);
});
modelBuilder.Entity("WebApplication1.Data.TestModel", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Content")
.HasColumnType("text");
b.Property<string>("Description")
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("TestModels");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}

View File

@ -1,236 +0,0 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace WebApplication1.Migrations.NoSharding.Migrations
{
public partial class initialCreate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
Name = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
NormalizedName = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
ConcurrencyStamp = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
UserName = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
NormalizedUserName = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
Email = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
NormalizedEmail = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
EmailConfirmed = table.Column<bool>(type: "boolean", nullable: false),
PasswordHash = table.Column<string>(type: "text", nullable: true),
SecurityStamp = table.Column<string>(type: "text", nullable: true),
ConcurrencyStamp = table.Column<string>(type: "text", nullable: true),
PhoneNumber = table.Column<string>(type: "text", nullable: true),
PhoneNumberConfirmed = table.Column<bool>(type: "boolean", nullable: false),
TwoFactorEnabled = table.Column<bool>(type: "boolean", nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
LockoutEnabled = table.Column<bool>(type: "boolean", nullable: false),
AccessFailedCount = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "TestModels",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
Content = table.Column<string>(type: "text", nullable: true),
Description = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_TestModels", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
RoleId = table.Column<string>(type: "text", nullable: false),
ClaimType = table.Column<string>(type: "text", nullable: true),
ClaimValue = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
UserId = table.Column<string>(type: "text", nullable: false),
ClaimType = table.Column<string>(type: "text", nullable: true),
ClaimValue = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: false),
ProviderKey = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: false),
ProviderDisplayName = table.Column<string>(type: "text", nullable: true),
UserId = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(type: "text", nullable: false),
RoleId = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<string>(type: "text", nullable: false),
LoginProvider = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: false),
Name = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: false),
Value = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
table.ForeignKey(
name: "FK_AspNetUserTokens_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName",
unique: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "TestModels");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "AspNetUsers");
}
}
}

View File

@ -1,27 +0,0 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace WebApplication1.Migrations.NoSharding.Migrations
{
public partial class TestModel_Add_CreationTime : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateTime>(
name: "CreationTime",
table: "TestModels",
type: "timestamp without time zone",
nullable: false,
defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified));
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "CreationTime",
table: "TestModels");
}
}
}

View File

@ -1,17 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="6.0.5" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\WebApplication1.Data\WebApplication1.Data.csproj" />
</ItemGroup>
</Project>

View File

@ -9,17 +9,17 @@ using WebApplication1.Data;
#nullable disable
namespace WebApplication1.Migrations.NoSharding.Migrations
namespace WebApplication1.Migrations.Sharding.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20220610090653_TestModel_Add_CreationTime")]
partial class TestModel_Add_CreationTime
[DbContext(typeof(AbstaractShardingDbContext))]
[Migration("20220712092732_TestModel_Id_RenameTo_Id2")]
partial class TestModel_Id_RenameTo_Id2
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "6.0.5")
.HasAnnotation("ProductVersion", "6.0.6")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
@ -224,12 +224,57 @@ namespace WebApplication1.Migrations.NoSharding.Migrations
b.ToTable("AspNetUserTokens", (string)null);
});
modelBuilder.Entity("WebApplication1.Data.TestModel", b =>
modelBuilder.Entity("WebApplication1.Data.Models.GuidShardingTable", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<string>("Name")
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("GuidShardingTables");
});
modelBuilder.Entity("WebApplication1.Data.Models.Order", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Name")
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Orders");
});
modelBuilder.Entity("WebApplication1.Data.Models.Student", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Name")
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Students");
});
modelBuilder.Entity("WebApplication1.Data.Models.TestModel", b =>
{
b.Property<Guid>("Id2")
.HasColumnType("uuid");
b.Property<string>("AfterShardingDb")
.HasColumnType("text");
b.Property<string>("Content")
.HasColumnType("text");
@ -239,11 +284,31 @@ namespace WebApplication1.Migrations.NoSharding.Migrations
b.Property<string>("Description")
.HasColumnType("text");
b.HasKey("Id");
b.Property<string>("TestNewField")
.HasColumnType("text");
b.HasKey("Id2");
b.ToTable("TestModels");
});
modelBuilder.Entity("WebApplication1.Data.Models.TestModelKey", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<string>("Key")
.HasMaxLength(36)
.HasColumnType("character varying(36)");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp without time zone");
b.HasKey("Id", "Key");
b.ToTable("TestModelKeys");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)

View File

@ -0,0 +1,130 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace WebApplication1.Migrations.Sharding.Migrations
{
public partial class TestModel_Id_RenameTo_Id2 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "Id",
table: "TestModels",
newName: "Id2");
migrationBuilder.AlterColumn<DateTime>(
name: "CreationTime",
table: "TestModels",
type: "timestamp without time zone",
nullable: false,
oldClrType: typeof(DateTime),
oldType: "timestamp with time zone");
migrationBuilder.AlterColumn<DateTime>(
name: "CreationDate",
table: "TestModelKeys",
type: "timestamp without time zone",
nullable: false,
oldClrType: typeof(DateTime),
oldType: "timestamp with time zone");
migrationBuilder.AlterColumn<string>(
name: "Name",
table: "AspNetUserTokens",
type: "character varying(128)",
maxLength: 128,
nullable: false,
oldClrType: typeof(string),
oldType: "text");
migrationBuilder.AlterColumn<string>(
name: "LoginProvider",
table: "AspNetUserTokens",
type: "character varying(128)",
maxLength: 128,
nullable: false,
oldClrType: typeof(string),
oldType: "text");
migrationBuilder.AlterColumn<string>(
name: "ProviderKey",
table: "AspNetUserLogins",
type: "character varying(128)",
maxLength: 128,
nullable: false,
oldClrType: typeof(string),
oldType: "text");
migrationBuilder.AlterColumn<string>(
name: "LoginProvider",
table: "AspNetUserLogins",
type: "character varying(128)",
maxLength: 128,
nullable: false,
oldClrType: typeof(string),
oldType: "text");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "Id2",
table: "TestModels",
newName: "Id");
migrationBuilder.AlterColumn<DateTime>(
name: "CreationTime",
table: "TestModels",
type: "timestamp with time zone",
nullable: false,
oldClrType: typeof(DateTime),
oldType: "timestamp without time zone");
migrationBuilder.AlterColumn<DateTime>(
name: "CreationDate",
table: "TestModelKeys",
type: "timestamp with time zone",
nullable: false,
oldClrType: typeof(DateTime),
oldType: "timestamp without time zone");
migrationBuilder.AlterColumn<string>(
name: "Name",
table: "AspNetUserTokens",
type: "text",
nullable: false,
oldClrType: typeof(string),
oldType: "character varying(128)",
oldMaxLength: 128);
migrationBuilder.AlterColumn<string>(
name: "LoginProvider",
table: "AspNetUserTokens",
type: "text",
nullable: false,
oldClrType: typeof(string),
oldType: "character varying(128)",
oldMaxLength: 128);
migrationBuilder.AlterColumn<string>(
name: "ProviderKey",
table: "AspNetUserLogins",
type: "text",
nullable: false,
oldClrType: typeof(string),
oldType: "character varying(128)",
oldMaxLength: 128);
migrationBuilder.AlterColumn<string>(
name: "LoginProvider",
table: "AspNetUserLogins",
type: "text",
nullable: false,
oldClrType: typeof(string),
oldType: "character varying(128)",
oldMaxLength: 128);
}
}
}

View File

@ -2,22 +2,24 @@
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using WebApplication1.Data;
#nullable disable
namespace WebApplication1.Migrations.NoSharding.Migrations
namespace WebApplication1.Migrations.Sharding.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
[DbContext(typeof(AbstaractShardingDbContext))]
[Migration("20220712093155_TestModel_Add_IntId")]
partial class TestModel_Add_IntId
{
protected override void BuildModel(ModelBuilder modelBuilder)
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "6.0.5")
.HasAnnotation("ProductVersion", "6.0.6")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
@ -222,12 +224,60 @@ namespace WebApplication1.Migrations.NoSharding.Migrations
b.ToTable("AspNetUserTokens", (string)null);
});
modelBuilder.Entity("WebApplication1.Data.TestModel", b =>
modelBuilder.Entity("WebApplication1.Data.Models.GuidShardingTable", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<string>("Name")
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("GuidShardingTables");
});
modelBuilder.Entity("WebApplication1.Data.Models.Order", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Name")
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Orders");
});
modelBuilder.Entity("WebApplication1.Data.Models.Student", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Name")
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Students");
});
modelBuilder.Entity("WebApplication1.Data.Models.TestModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("AfterShardingDb")
.HasColumnType("text");
b.Property<string>("Content")
.HasColumnType("text");
@ -237,11 +287,31 @@ namespace WebApplication1.Migrations.NoSharding.Migrations
b.Property<string>("Description")
.HasColumnType("text");
b.Property<string>("TestNewField")
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("TestModels");
});
modelBuilder.Entity("WebApplication1.Data.Models.TestModelKey", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<string>("Key")
.HasMaxLength(36)
.HasColumnType("character varying(36)");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp without time zone");
b.HasKey("Id", "Key");
b.ToTable("TestModelKeys");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)

View File

@ -0,0 +1,58 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace WebApplication1.Migrations.Sharding.Migrations
{
public partial class TestModel_Add_IntId : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropPrimaryKey(
name: "PK_TestModels",
table: "TestModels");
migrationBuilder.DropColumn(
name: "Id2",
table: "TestModels");
migrationBuilder.AddColumn<int>(
name: "Id",
table: "TestModels",
type: "integer",
nullable: false,
defaultValue: 0)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
migrationBuilder.AddPrimaryKey(
name: "PK_TestModels",
table: "TestModels",
column: "Id");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropPrimaryKey(
name: "PK_TestModels",
table: "TestModels");
migrationBuilder.DropColumn(
name: "Id",
table: "TestModels");
migrationBuilder.AddColumn<Guid>(
name: "Id2",
table: "TestModels",
type: "uuid",
nullable: false,
defaultValue: new Guid("00000000-0000-0000-0000-000000000000"));
migrationBuilder.AddPrimaryKey(
name: "PK_TestModels",
table: "TestModels",
column: "Id2");
}
}
}

View File

@ -17,7 +17,7 @@ namespace WebApplication1.Migrations.Sharding.Migrations
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "6.0.5")
.HasAnnotation("ProductVersion", "6.0.6")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
@ -165,10 +165,12 @@ namespace WebApplication1.Migrations.Sharding.Migrations
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("text");
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<string>("ProviderKey")
.HasColumnType("text");
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<string>("ProviderDisplayName")
.HasColumnType("text");
@ -205,10 +207,12 @@ namespace WebApplication1.Migrations.Sharding.Migrations
.HasColumnType("text");
b.Property<string>("LoginProvider")
.HasColumnType("text");
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<string>("Name")
.HasColumnType("text");
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<string>("Value")
.HasColumnType("text");
@ -263,9 +267,11 @@ namespace WebApplication1.Migrations.Sharding.Migrations
modelBuilder.Entity("WebApplication1.Data.Models.TestModel", b =>
{
b.Property<Guid>("Id")
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("AfterShardingDb")
.HasColumnType("text");
@ -274,7 +280,7 @@ namespace WebApplication1.Migrations.Sharding.Migrations
.HasColumnType("text");
b.Property<DateTime>("CreationTime")
.HasColumnType("timestamp with time zone");
.HasColumnType("timestamp without time zone");
b.Property<string>("Description")
.HasColumnType("text");
@ -297,7 +303,7 @@ namespace WebApplication1.Migrations.Sharding.Migrations
.HasColumnType("character varying(36)");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp with time zone");
.HasColumnType("timestamp without time zone");
b.HasKey("Id", "Key");

View File

@ -8,7 +8,7 @@
<ItemGroup>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="6.0.5" />
<PackageReference Include="ShardingCore" Version="6.5.0.11" />
<PackageReference Include="ShardingCore" Version="6.6.0.9" />
</ItemGroup>
<ItemGroup>

View File

@ -1,6 +0,0 @@
// 解决 PostgreSQL 在.NET 6.0 使用 DateTime 类型抛出异常timestamp with time zone
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); // 启用旧时间戳行为
AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true); // 禁用日期时间无限转换
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");

View File

@ -1,80 +0,0 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.Extensions.DependencyInjection;
using ShardingCore;
using ShardingCore.Bootstrappers;
using ShardingCore.TableExists;
using WebApplication1.Data;
using WebApplication1.Data.Extensions;
using WebApplication1.Data.Sharding;
namespace WebApplication1.Migrations.Tool
{
public class ShardingDesignTimeDbContextFactory : IDesignTimeDbContextFactory<AbstaractShardingDbContext>
{
const string migrationsAssemblyName = "WebApplication1.Migrations.Sharding";
static ShardingDesignTimeDbContextFactory()
{
var services = new ServiceCollection();
services.AddShardingDbContext<AbstaractShardingDbContext>()
.AddEntityConfig(o =>
{
o.CreateDataBaseOnlyOnStart = true; // 启动时创建数据库
o.CreateShardingTableOnStart = false; // 如果您使用code-first建议选择false
o.EnsureCreatedWithOutShardingTable = false; // 如果您使用code-first建议修改为fsle
o.IgnoreCreateTableError = false; // 如果不忽略就会输出warning的日志
//添加分库路由
o.AddShardingDataSourceRoute<TestModelVirtualDataSourceRoute>();
//添加分表路由
o.AddShardingTableRoute<TestModelVirtualTableRoute>();
o.AddShardingTableRoute<StudentVirtualTableRoute>();
o.AddShardingTableRoute<GuidShardingTableVirtualTableRoute>();
})
.AddConfig(op =>
{
op.ConfigId = "c1";
// 添加这个对象的字符串创建dbcontext 优先级低 优先采用AddConfig下的
op.UseShardingQuery((conStr, builder) =>
{
builder.UseNpgsql(conStr, opt => opt.MigrationsAssembly(migrationsAssemblyName));
});
// 添加这个对象的链接创建dbcontext 优先级低 优先采用AddConfig下的
op.UseShardingTransaction((connection, builder) =>
{
builder.UseNpgsql(connection, opt => opt.MigrationsAssembly(migrationsAssemblyName));
});
op.ReplaceTableEnsureManager(sp => new SqlServerTableEnsureManager<AbstaractShardingDbContext>());
op.AddDefaultDataSource("ds0", "server=127.0.0.1;port=5432;uid=postgres;pwd=3#SanJing;database=shardingCoreDemo;");
op.UseShellDbContextConfigure(builder =>
{
builder.ReplaceService<IMigrationsSqlGenerator, ShardingMigrationsSqlGenerator<AbstaractShardingDbContext>>()
//.ReplaceService<IMigrationsModelDiffer, RemoveForeignKeyMigrationsModelDiffer>();//如果需要移除外键可以添加这个
;
});
}).EnsureConfig();
services.AddLogging();
var buildServiceProvider = services.BuildServiceProvider();
ShardingContainer.SetServices(buildServiceProvider);
ShardingContainer.GetService<IShardingBootstrapper>().Start();
buildServiceProvider.InitialDynamicVirtualDataSource();
}
public AbstaractShardingDbContext CreateDbContext(string[] args)
{
return ShardingContainer.GetService<AbstaractShardingDbContext>();
}
}
}

View File

@ -1,14 +0,0 @@
START TRANSACTION;
CREATE TABLE "TestModelKeys" (
"Id" uuid NOT NULL,
"Key" character varying(36) NOT NULL,
"CreationDate" timestamp with time zone NOT NULL,
CONSTRAINT "PK_TestModelKeys" PRIMARY KEY ("Id", "Key")
);
INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
VALUES ('20220616075026_TestModelKey_Create', '6.0.5');
COMMIT;

View File

@ -1,24 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<!--<Nullable>enable</Nullable>-->
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.6">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="6.0.5" />
<PackageReference Include="ShardingCore" Version="6.5.0.11" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\WebApplication1.Data\WebApplication1.Data.csproj" />
<ProjectReference Include="..\WebApplication1.Migrations.Sharding\WebApplication1.Migrations.Sharding.csproj" />
</ItemGroup>
</Project>

View File

@ -1,249 +0,0 @@
CREATE TABLE IF NOT EXISTS "__EFMigrationsHistory" (
"MigrationId" character varying(150) NOT NULL,
"ProductVersion" character varying(32) NOT NULL,
CONSTRAINT "PK___EFMigrationsHistory" PRIMARY KEY ("MigrationId")
);
START TRANSACTION;
CREATE TABLE "AspNetRoles" (
"Id" text NOT NULL,
"Name" character varying(256) NULL,
"NormalizedName" character varying(256) NULL,
"ConcurrencyStamp" text NULL,
CONSTRAINT "PK_AspNetRoles" PRIMARY KEY ("Id")
);
CREATE TABLE "AspNetUsers" (
"Id" text NOT NULL,
"UserName" character varying(256) NULL,
"NormalizedUserName" character varying(256) NULL,
"Email" character varying(256) NULL,
"NormalizedEmail" character varying(256) NULL,
"EmailConfirmed" boolean NOT NULL,
"PasswordHash" text NULL,
"SecurityStamp" text NULL,
"ConcurrencyStamp" text NULL,
"PhoneNumber" text NULL,
"PhoneNumberConfirmed" boolean NOT NULL,
"TwoFactorEnabled" boolean NOT NULL,
"LockoutEnd" timestamp with time zone NULL,
"LockoutEnabled" boolean NOT NULL,
"AccessFailedCount" integer NOT NULL,
CONSTRAINT "PK_AspNetUsers" PRIMARY KEY ("Id")
);
CREATE TABLE "GuidShardingTables_001" (
"Id" uuid NOT NULL,
"Name" text NULL,
CONSTRAINT "PK_GuidShardingTables_001" PRIMARY KEY ("Id")
);
CREATE TABLE "GuidShardingTables_005" (
"Id" uuid NOT NULL,
"Name" text NULL,
CONSTRAINT "PK_GuidShardingTables_005" PRIMARY KEY ("Id")
);
CREATE TABLE "GuidShardingTables_003" (
"Id" uuid NOT NULL,
"Name" text NULL,
CONSTRAINT "PK_GuidShardingTables_003" PRIMARY KEY ("Id")
);
CREATE TABLE "GuidShardingTables_004" (
"Id" uuid NOT NULL,
"Name" text NULL,
CONSTRAINT "PK_GuidShardingTables_004" PRIMARY KEY ("Id")
);
CREATE TABLE "GuidShardingTables_002" (
"Id" uuid NOT NULL,
"Name" text NULL,
CONSTRAINT "PK_GuidShardingTables_002" PRIMARY KEY ("Id")
);
CREATE TABLE "GuidShardingTables_000" (
"Id" uuid NOT NULL,
"Name" text NULL,
CONSTRAINT "PK_GuidShardingTables_000" PRIMARY KEY ("Id")
);
CREATE TABLE "Orders" (
"Id" uuid NOT NULL,
"Name" text NULL,
CONSTRAINT "PK_Orders" PRIMARY KEY ("Id")
);
CREATE TABLE "Students_001" (
"Id" integer GENERATED BY DEFAULT AS IDENTITY,
"Name" text NULL,
CONSTRAINT "PK_Students_001" PRIMARY KEY ("Id")
);
CREATE TABLE "Students_002" (
"Id" integer GENERATED BY DEFAULT AS IDENTITY,
"Name" text NULL,
CONSTRAINT "PK_Students_002" PRIMARY KEY ("Id")
);
CREATE TABLE "Students_005" (
"Id" integer GENERATED BY DEFAULT AS IDENTITY,
"Name" text NULL,
CONSTRAINT "PK_Students_005" PRIMARY KEY ("Id")
);
CREATE TABLE "Students_004" (
"Id" integer GENERATED BY DEFAULT AS IDENTITY,
"Name" text NULL,
CONSTRAINT "PK_Students_004" PRIMARY KEY ("Id")
);
CREATE TABLE "Students_000" (
"Id" integer GENERATED BY DEFAULT AS IDENTITY,
"Name" text NULL,
CONSTRAINT "PK_Students_000" PRIMARY KEY ("Id")
);
CREATE TABLE "Students_003" (
"Id" integer GENERATED BY DEFAULT AS IDENTITY,
"Name" text NULL,
CONSTRAINT "PK_Students_003" PRIMARY KEY ("Id")
);
CREATE TABLE "TestModels_202202" (
"Id" uuid NOT NULL,
"Content" text NULL,
"Description" text NULL,
"CreationTime" timestamp with time zone NOT NULL,
"TestNewField" text NULL,
CONSTRAINT "PK_TestModels_202202" PRIMARY KEY ("Id")
);
CREATE TABLE "TestModels_202203" (
"Id" uuid NOT NULL,
"Content" text NULL,
"Description" text NULL,
"CreationTime" timestamp with time zone NOT NULL,
"TestNewField" text NULL,
CONSTRAINT "PK_TestModels_202203" PRIMARY KEY ("Id")
);
CREATE TABLE "TestModels_202205" (
"Id" uuid NOT NULL,
"Content" text NULL,
"Description" text NULL,
"CreationTime" timestamp with time zone NOT NULL,
"TestNewField" text NULL,
CONSTRAINT "PK_TestModels_202205" PRIMARY KEY ("Id")
);
CREATE TABLE "TestModels_202204" (
"Id" uuid NOT NULL,
"Content" text NULL,
"Description" text NULL,
"CreationTime" timestamp with time zone NOT NULL,
"TestNewField" text NULL,
CONSTRAINT "PK_TestModels_202204" PRIMARY KEY ("Id")
);
CREATE TABLE "TestModels_202201" (
"Id" uuid NOT NULL,
"Content" text NULL,
"Description" text NULL,
"CreationTime" timestamp with time zone NOT NULL,
"TestNewField" text NULL,
CONSTRAINT "PK_TestModels_202201" PRIMARY KEY ("Id")
);
CREATE TABLE "TestModels_202206" (
"Id" uuid NOT NULL,
"Content" text NULL,
"Description" text NULL,
"CreationTime" timestamp with time zone NOT NULL,
"TestNewField" text NULL,
CONSTRAINT "PK_TestModels_202206" PRIMARY KEY ("Id")
);
CREATE TABLE "AspNetRoleClaims" (
"Id" integer GENERATED BY DEFAULT AS IDENTITY,
"RoleId" text NOT NULL,
"ClaimType" text NULL,
"ClaimValue" text NULL,
CONSTRAINT "PK_AspNetRoleClaims" PRIMARY KEY ("Id"),
CONSTRAINT "FK_AspNetRoleClaims_AspNetRoles_RoleId" FOREIGN KEY ("RoleId") REFERENCES "AspNetRoles" ("Id") ON DELETE CASCADE
);
CREATE TABLE "AspNetUserClaims" (
"Id" integer GENERATED BY DEFAULT AS IDENTITY,
"UserId" text NOT NULL,
"ClaimType" text NULL,
"ClaimValue" text NULL,
CONSTRAINT "PK_AspNetUserClaims" PRIMARY KEY ("Id"),
CONSTRAINT "FK_AspNetUserClaims_AspNetUsers_UserId" FOREIGN KEY ("UserId") REFERENCES "AspNetUsers" ("Id") ON DELETE CASCADE
);
CREATE TABLE "AspNetUserLogins" (
"LoginProvider" text NOT NULL,
"ProviderKey" text NOT NULL,
"ProviderDisplayName" text NULL,
"UserId" text NOT NULL,
CONSTRAINT "PK_AspNetUserLogins" PRIMARY KEY ("LoginProvider", "ProviderKey"),
CONSTRAINT "FK_AspNetUserLogins_AspNetUsers_UserId" FOREIGN KEY ("UserId") REFERENCES "AspNetUsers" ("Id") ON DELETE CASCADE
);
CREATE TABLE "AspNetUserRoles" (
"UserId" text NOT NULL,
"RoleId" text NOT NULL,
CONSTRAINT "PK_AspNetUserRoles" PRIMARY KEY ("UserId", "RoleId"),
CONSTRAINT "FK_AspNetUserRoles_AspNetRoles_RoleId" FOREIGN KEY ("RoleId") REFERENCES "AspNetRoles" ("Id") ON DELETE CASCADE,
CONSTRAINT "FK_AspNetUserRoles_AspNetUsers_UserId" FOREIGN KEY ("UserId") REFERENCES "AspNetUsers" ("Id") ON DELETE CASCADE
);
CREATE TABLE "AspNetUserTokens" (
"UserId" text NOT NULL,
"LoginProvider" text NOT NULL,
"Name" text NOT NULL,
"Value" text NULL,
CONSTRAINT "PK_AspNetUserTokens" PRIMARY KEY ("UserId", "LoginProvider", "Name"),
CONSTRAINT "FK_AspNetUserTokens_AspNetUsers_UserId" FOREIGN KEY ("UserId") REFERENCES "AspNetUsers" ("Id") ON DELETE CASCADE
);
CREATE INDEX "IX_AspNetRoleClaims_RoleId" ON "AspNetRoleClaims" ("RoleId");
CREATE UNIQUE INDEX "RoleNameIndex" ON "AspNetRoles" ("NormalizedName");
CREATE INDEX "IX_AspNetUserClaims_UserId" ON "AspNetUserClaims" ("UserId");
CREATE INDEX "IX_AspNetUserLogins_UserId" ON "AspNetUserLogins" ("UserId");
CREATE INDEX "IX_AspNetUserRoles_RoleId" ON "AspNetUserRoles" ("RoleId");
CREATE INDEX "EmailIndex" ON "AspNetUsers" ("NormalizedEmail");
CREATE UNIQUE INDEX "UserNameIndex" ON "AspNetUsers" ("NormalizedUserName");
INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
VALUES ('20220615110332_InitialCreate', '6.0.5');
COMMIT;
START TRANSACTION;
ALTER TABLE "TestModels_202202" ADD "AfterShardingDb" text NULL;
ALTER TABLE "TestModels_202203" ADD "AfterShardingDb" text NULL;
ALTER TABLE "TestModels_202205" ADD "AfterShardingDb" text NULL;
ALTER TABLE "TestModels_202204" ADD "AfterShardingDb" text NULL;
ALTER TABLE "TestModels_202201" ADD "AfterShardingDb" text NULL;
ALTER TABLE "TestModels_202206" ADD "AfterShardingDb" text NULL;
INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
VALUES ('20220615152140_TestModel_Add_AfterShardingDb', '6.0.5');
COMMIT;

View File

@ -1,5 +1,7 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using ShardingCore.Core.RuntimeContexts;
using ShardingCore.Helpers;
using System;
using System.Collections.Generic;
@ -15,13 +17,15 @@ namespace WebApplication1.Pages
{
private readonly AbstaractShardingDbContext db;
private readonly IShardingRuntimeContext runtimeContext;
[BindProperty]
public BatchCreateModel CreateModel { get; set; }
public BatchCreateDbKeyModel(AbstaractShardingDbContext db)
public BatchCreateDbKeyModel(AbstaractShardingDbContext db, IShardingRuntimeContext runtimeContext)
{
this.db = db;
this.runtimeContext = runtimeContext;
}
public void OnGet()
@ -37,6 +41,11 @@ namespace WebApplication1.Pages
keyList.Add(i.ToString().PadLeft(CreateModel.Len, '0'));
}
// 读取并写入到配置
var dblist = JsonFileHelper.Read<List<string>>(AppContext.BaseDirectory, TestModelVirtualDataSourceRoute.ConfigFileName);
dblist.AddRange(keyList);
JsonFileHelper.Save(AppContext.BaseDirectory, TestModelVirtualDataSourceRoute.ConfigFileName, dblist);
foreach (var item in keyList)
{
db.TestModelKeys.Add(new TestModelKey { Key = item });
@ -46,13 +55,10 @@ namespace WebApplication1.Pages
foreach (var item in keyList)
{
// 动态新增数据源
DynamicShardingHelper.DynamicAppendDataSource<AbstaractShardingDbContext>("c1", item, $"server=127.0.0.1;port=5432;uid=postgres;pwd=3#SanJing;database=shardingCoreDemo_{item};");
DynamicShardingHelper.DynamicAppendDataSourceOnly(runtimeContext, item, $"server=127.0.0.1;port=5432;uid=postgres;pwd=3#SanJing;database=shardingCoreDemo_{item};");
}
// 读取并写入到配置
var dblist = JsonFileHelper.Read<List<string>>(AppContext.BaseDirectory, TestModelVirtualDataSourceRoute.ConfigFileName);
dblist.AddRange(keyList);
JsonFileHelper.Save(AppContext.BaseDirectory, TestModelVirtualDataSourceRoute.ConfigFileName, dblist);
db.Database.Migrate();
return RedirectToPage("DbKeyMan");

View File

@ -1,5 +1,7 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using ShardingCore.Core.RuntimeContexts;
using ShardingCore.Helpers;
using System;
using System.Collections.Generic;
@ -14,13 +16,15 @@ namespace WebApplication1.Pages
{
private readonly AbstaractShardingDbContext db;
private readonly IShardingRuntimeContext runtimeContext;
[BindProperty]
public string Key { get; set; }
public CreateDbKeyModel(AbstaractShardingDbContext db)
public CreateDbKeyModel(AbstaractShardingDbContext db, IShardingRuntimeContext runtimeContext)
{
this.db = db;
this.runtimeContext = runtimeContext;
}
public void OnGet()
@ -40,7 +44,9 @@ namespace WebApplication1.Pages
JsonFileHelper.Save(AppContext.BaseDirectory, TestModelVirtualDataSourceRoute.ConfigFileName, dblist);
// ¶¯Ì¬ÐÂÔöÊý¾ÝÔ´
DynamicShardingHelper.DynamicAppendDataSource<AbstaractShardingDbContext>("c1", Key, $"server=127.0.0.1;port=5432;uid=postgres;pwd=3#SanJing;database=shardingCoreDemo_{Key};");
DynamicShardingHelper.DynamicAppendDataSourceOnly(runtimeContext, Key, $"server=127.0.0.1;port=5432;uid=postgres;pwd=3#SanJing;database=shardingCoreDemo_{Key};");
//DynamicShardingHelper.DynamicAppendDataSourceOnly(runtimeContext, Key, $"server=127.0.0.1;port=5432;uid=postgres;pwd=3#SanJing;database=shardingCoreDemo_{Key};");
db.Database.Migrate();
return RedirectToPage("DbKeyMan");
}

View File

@ -5,9 +5,11 @@ using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using ShardingCore;
using ShardingCore.Bootstrappers;
using ShardingCore.Core;
using ShardingCore.TableExists;
using ShardingCore.TableExists.Abstractions;
using System;
using System.Diagnostics;
using WebApplication1.Data;
using WebApplication1.Data.Extensions;
using WebApplication1.Data.Sharding;
@ -22,22 +24,16 @@ var configuration = builder.Configuration;
var npgConnectionString = configuration.GetConnectionString("DefaultConnection");
const string migrationsAssemblyName = "WebApplication1.Migrations.Sharding";
#region dbcontext
var watch = new Stopwatch();
watch.Start();
Console.WriteLine("开始计时");
//services.AddDbContext<ApplicationDbContext>(options =>
//{
// options.UseNpgsql(npgConnectionString, x => x.MigrationsAssembly(migrationsAssemblyName));
//});
#region dbcontext
services
.AddShardingDbContext<AbstaractShardingDbContext>()
.AddEntityConfig(o =>
.UseRouteConfig(o =>
{
o.CreateDataBaseOnlyOnStart = true; // 启动时创建数据库
o.CreateShardingTableOnStart = true; // 如果您使用code-first建议选择false //! 这里需要注意如果是迁移更新必须设置为false然后再开启用于启动时候自动创建分片
o.EnsureCreatedWithOutShardingTable = false; // 如果您使用code-first建议修改为fsle
o.IgnoreCreateTableError = false; // 如果不忽略就会输出warning的日志
//添加分库路由
o.AddShardingDataSourceRoute<TestModelVirtualDataSourceRoute>();
@ -46,32 +42,52 @@ services
o.AddShardingTableRoute<StudentVirtualTableRoute>();
o.AddShardingTableRoute<GuidShardingTableVirtualTableRoute>();
})
.AddConfig(op =>
.UseConfig(op =>
{
op.ConfigId = "c1";
// 添加这个对象的字符串创建dbcontext 优先级低 优先采用AddConfig下的
op.UseShardingQuery((connString, builder) => builder.UseNpgsql(connString, opt => opt.MigrationsAssembly(migrationsAssemblyName)));
// 添加这个对象的链接创建dbcontext 优先级低 优先采用AddConfig下的
op.UseShardingTransaction((connection, builder) => builder.UseNpgsql(connection, opt => opt.MigrationsAssembly(migrationsAssemblyName)));
op.ReplaceTableEnsureManager(sp => new SqlServerTableEnsureManager<AbstaractShardingDbContext>());
op.AddDefaultDataSource("ds0", npgConnectionString);
//op.AddExtraDataSource(sp => new Dictionary<string, string>()
//{
// {"11","server=127.0.0.1;port=5432;uid=postgres;pwd=3#SanJing;database=shardingCoreDemo_11;"},
// {"22","server=127.0.0.1;port=5432;uid=postgres;pwd=3#SanJing;database=shardingCoreDemo_22;"},
// //{"C","server=127.0.0.1;port=5432;uid=postgres;pwd=3#SanJing;database=shardingCoreDemoC;"},
//});
op.UseShellDbContextConfigure(builder =>
//当无法获取路由时会返回默认值而不是报错
op.ThrowIfQueryRouteNotMatch = false;
//忽略建表错误compensate table和table creator
op.IgnoreCreateTableError = true;
//迁移时使用的并行线程数(分库有效)defaultShardingDbContext.Database.Migrate()
op.MigrationParallelCount = Environment.ProcessorCount * 3;
//补偿表创建并行线程数 调用UseAutoTryCompensateTable有效
op.CompensateTableParallelCount = Environment.ProcessorCount;
//最大连接数限制
op.MaxQueryConnectionsLimit = Environment.ProcessorCount;
//链接模式系统默认
op.ConnectionMode = ConnectionModeEnum.SYSTEM_AUTO;
//如何通过字符串查询创建DbContext
op.UseShardingQuery((connString, builder) =>
{
builder.ReplaceService<IMigrationsSqlGenerator, ShardingMigrationsSqlGenerator<AbstaractShardingDbContext>>()
//.ReplaceService<IMigrationsModelDiffer, RemoveForeignKeyMigrationsModelDiffer>();//如果需要移除外键可以添加这个
builder.UseNpgsql(connString, opt => opt.MigrationsAssembly(migrationsAssemblyName))
//.UseLoggerFactory(efLogger)
;
});
//如何通过事务创建DbContext
op.UseShardingTransaction((connection, builder) =>
{
builder.UseNpgsql(connection, opt => opt.MigrationsAssembly(migrationsAssemblyName))
//.UseLoggerFactory(efLogger)
;
});
//添加默认数据源
op.AddDefaultDataSource("ds0", npgConnectionString);
//添加额外数据源
//op.AddExtraDataSource(sp =>
//{
// return new Dictionary<string, string>()
// {
// {"11","server=127.0.0.1;port=5432;uid=postgres;pwd=3#SanJing;database=shardingCoreDemo_11;"},
// {"22","server=127.0.0.1;port=5432;uid=postgres;pwd=3#SanJing;database=shardingCoreDemo_22;"},
// };
//});
op.UseShardingMigrationConfigure(configure =>
{
configure.ReplaceService<IMigrationsSqlGenerator, ShardingMigrationsSqlGenerator<AbstaractShardingDbContext>>();
});
})
.EnsureConfig();
.ReplaceService<ITableEnsureManager, SqlServerTableEnsureManager>()
.AddShardingCore();
#endregion
@ -86,11 +102,13 @@ services.AddDatabaseDeveloperPageExceptionFilter();
var app = builder.Build();
var shardingBootstrapper = app.Services.GetRequiredService<IShardingBootstrapper>();
shardingBootstrapper.Start();
//启动ShardingCore创建表任务(不调用也可以使用ShardingCore)
//不调用会导致定时任务不会开启
app.Services.UseAutoShardingCreate();
// 初始化动态数据源
app.Services.InitialDynamicVirtualDataSource();
//启动进行表补偿(不调用也可以使用ShardingCore)
app.Services.UseAutoTryCompensateTable(10);
app.UseHsts();
app.UseHttpsRedirection();
@ -103,10 +121,7 @@ app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); });
// 使用迁移
using var scope = app.Services.CreateScope();
// 初始化数据库及启用迁移设置
DbInitializationProvider.Initialize<AbstaractShardingDbContext>(scope.ServiceProvider);
watch.Stop();
Console.WriteLine($"耗时:{watch.Elapsed.TotalMilliseconds} 毫秒");
await app.RunAsync();

View File

@ -13,7 +13,7 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="6.0.5" />
<PackageReference Include="ShardingCore" Version="6.5.0.11" />
<PackageReference Include="ShardingCore" Version="6.6.0.9" />
</ItemGroup>
<ItemGroup>

View File

@ -1,9 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Default": "debug",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
"Microsoft.Hosting.Lifetime": "debug"
}
}
}