diff --git a/samples/Samples.DynamicDb.Npgsql/ShardingCoreDemo.sln b/samples/Samples.DynamicDb.Npgsql/ShardingCoreDemo.sln index 894701f0..72f08cfc 100644 --- a/samples/Samples.DynamicDb.Npgsql/ShardingCoreDemo.sln +++ b/samples/Samples.DynamicDb.Npgsql/ShardingCoreDemo.sln @@ -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 diff --git a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Data/AbstaractShardingDbContext.cs b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Data/AbstaractShardingDbContext.cs index 18d3d64a..cdfe5993 100644 --- a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Data/AbstaractShardingDbContext.cs +++ b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Data/AbstaractShardingDbContext.cs @@ -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 options) : base(options) { var wrapOptionsExtension = options.FindExtension(); if (wrapOptionsExtension != null) - _shardingDbContextExecutor = (IShardingDbContextExecutor)Activator.CreateInstance(typeof(ShardingDbContextExecutor<>).GetGenericType0(GetType()), this); + _shardingDbContextExecutor = new ShardingDbContextExecutor(this); } #region 接口实现 @@ -35,7 +37,7 @@ namespace WebApplication1.Data /// /// 是否是真正的执行者 /// - private bool isExecutor => _shardingDbContextExecutor == null; + private bool IsExecutor => _shardingDbContextExecutor == null; /// /// 读写分离优先级 @@ -131,7 +133,7 @@ namespace WebApplication1.Data /// /// /// - 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 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 Add(TEntity entity) { - if (isExecutor) return base.Add(entity); + if (IsExecutor) return base.Add(entity); return CreateGenericDbContext(entity).Add(entity); } public override ValueTask> AddAsync(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 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 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 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 Attach(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 entities) { - if (isExecutor) + if (IsExecutor) { base.AttachRange(entities); return; @@ -369,35 +371,35 @@ namespace WebApplication1.Data public override EntityEntry Entry(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 Update(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 entities) { - if (isExecutor) + if (IsExecutor) { base.UpdateRange(entities); return; @@ -443,21 +445,21 @@ namespace WebApplication1.Data public override EntityEntry Remove(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 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 SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken()) { - if (isExecutor) + if (IsExecutor) return base.SaveChangesAsync(cancellationToken); return this.SaveChangesAsync(true, cancellationToken); } public override async Task 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().HasKey(t => new { t.Id, t.Key }); builder.Entity().Property(o => o.Key).IsRequired().HasMaxLength(36); } - } } diff --git a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Data/Extensions/ServicesExtensions.cs b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Data/Extensions/ServicesExtensions.cs index 0dea89a7..5d058616 100644 --- a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Data/Extensions/ServicesExtensions.cs +++ b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Data/Extensions/ServicesExtensions.cs @@ -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(); - db.Database.EnsureCreated(); + var runtimeContext = scope.ServiceProvider.GetRequiredService(); + //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("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; diff --git a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Data/Models/TestModel.cs b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Data/Models/TestModel.cs index 50fbf161..35f42d2a 100644 --- a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Data/Models/TestModel.cs +++ b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Data/Models/TestModel.cs @@ -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; } = ""; diff --git a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Data/Sharding/GuidShardingTableVirtualTableRoute.cs b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Data/Sharding/GuidShardingTableVirtualTableRoute.cs index 54656613..75b710c3 100644 --- a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Data/Sharding/GuidShardingTableVirtualTableRoute.cs +++ b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Data/Sharding/GuidShardingTableVirtualTableRoute.cs @@ -7,7 +7,7 @@ namespace WebApplication1.Data.Sharding public class GuidShardingTableVirtualTableRoute : AbstractSimpleShardingModKeyStringVirtualTableRoute { - public GuidShardingTableVirtualTableRoute() : base(3, 6, '0') + public GuidShardingTableVirtualTableRoute() : base(3, 6) { } diff --git a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Data/Sharding/StudentVirtualTableRoute.cs b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Data/Sharding/StudentVirtualTableRoute.cs index 6ed0e573..f98d73f7 100644 --- a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Data/Sharding/StudentVirtualTableRoute.cs +++ b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Data/Sharding/StudentVirtualTableRoute.cs @@ -7,7 +7,7 @@ namespace WebApplication1.Data.Sharding public class StudentVirtualTableRoute : AbstractSimpleShardingModKeyStringVirtualTableRoute { - public StudentVirtualTableRoute() : base(3, 6, '0') + public StudentVirtualTableRoute() : base(3, 6) { } diff --git a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Data/ShardingMigrationsSqlGenerator.cs b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Data/ShardingMigrationsSqlGenerator.cs index 90b368e6..b39657c9 100644 --- a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Data/ShardingMigrationsSqlGenerator.cs +++ b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Data/ShardingMigrationsSqlGenerator.cs @@ -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 /// public class ShardingMigrationsSqlGenerator : 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(operation, builder, Dependencies.SqlGenerationHelper, addCmds); + MigrationHelper.Generate(runtimeContext, operation, builder, Dependencies.SqlGenerationHelper, addCmds); } } diff --git a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Data/WebApplication1.Data.csproj b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Data/WebApplication1.Data.csproj index 5409fd5d..f369463b 100644 --- a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Data/WebApplication1.Data.csproj +++ b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Data/WebApplication1.Data.csproj @@ -7,7 +7,7 @@ - + \ No newline at end of file diff --git a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.NoSharding/Migrations/20220610041036_initialCreate.Designer.cs b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.NoSharding/Migrations/20220610041036_initialCreate.Designer.cs deleted file mode 100644 index b6e5f90f..00000000 --- a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.NoSharding/Migrations/20220610041036_initialCreate.Designer.cs +++ /dev/null @@ -1,297 +0,0 @@ -// -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("Id") - .HasColumnType("text"); - - b.Property("ConcurrencyStamp") - .IsConcurrencyToken() - .HasColumnType("text"); - - b.Property("Name") - .HasMaxLength(256) - .HasColumnType("character varying(256)"); - - b.Property("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", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer"); - - NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - - b.Property("ClaimType") - .HasColumnType("text"); - - b.Property("ClaimValue") - .HasColumnType("text"); - - b.Property("RoleId") - .IsRequired() - .HasColumnType("text"); - - b.HasKey("Id"); - - b.HasIndex("RoleId"); - - b.ToTable("AspNetRoleClaims", (string)null); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => - { - b.Property("Id") - .HasColumnType("text"); - - b.Property("AccessFailedCount") - .HasColumnType("integer"); - - b.Property("ConcurrencyStamp") - .IsConcurrencyToken() - .HasColumnType("text"); - - b.Property("Email") - .HasMaxLength(256) - .HasColumnType("character varying(256)"); - - b.Property("EmailConfirmed") - .HasColumnType("boolean"); - - b.Property("LockoutEnabled") - .HasColumnType("boolean"); - - b.Property("LockoutEnd") - .HasColumnType("timestamp with time zone"); - - b.Property("NormalizedEmail") - .HasMaxLength(256) - .HasColumnType("character varying(256)"); - - b.Property("NormalizedUserName") - .HasMaxLength(256) - .HasColumnType("character varying(256)"); - - b.Property("PasswordHash") - .HasColumnType("text"); - - b.Property("PhoneNumber") - .HasColumnType("text"); - - b.Property("PhoneNumberConfirmed") - .HasColumnType("boolean"); - - b.Property("SecurityStamp") - .HasColumnType("text"); - - b.Property("TwoFactorEnabled") - .HasColumnType("boolean"); - - b.Property("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", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer"); - - NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - - b.Property("ClaimType") - .HasColumnType("text"); - - b.Property("ClaimValue") - .HasColumnType("text"); - - b.Property("UserId") - .IsRequired() - .HasColumnType("text"); - - b.HasKey("Id"); - - b.HasIndex("UserId"); - - b.ToTable("AspNetUserClaims", (string)null); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => - { - b.Property("LoginProvider") - .HasMaxLength(128) - .HasColumnType("character varying(128)"); - - b.Property("ProviderKey") - .HasMaxLength(128) - .HasColumnType("character varying(128)"); - - b.Property("ProviderDisplayName") - .HasColumnType("text"); - - b.Property("UserId") - .IsRequired() - .HasColumnType("text"); - - b.HasKey("LoginProvider", "ProviderKey"); - - b.HasIndex("UserId"); - - b.ToTable("AspNetUserLogins", (string)null); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => - { - b.Property("UserId") - .HasColumnType("text"); - - b.Property("RoleId") - .HasColumnType("text"); - - b.HasKey("UserId", "RoleId"); - - b.HasIndex("RoleId"); - - b.ToTable("AspNetUserRoles", (string)null); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => - { - b.Property("UserId") - .HasColumnType("text"); - - b.Property("LoginProvider") - .HasMaxLength(128) - .HasColumnType("character varying(128)"); - - b.Property("Name") - .HasMaxLength(128) - .HasColumnType("character varying(128)"); - - b.Property("Value") - .HasColumnType("text"); - - b.HasKey("UserId", "LoginProvider", "Name"); - - b.ToTable("AspNetUserTokens", (string)null); - }); - - modelBuilder.Entity("WebApplication1.Data.TestModel", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("uuid"); - - b.Property("Content") - .HasColumnType("text"); - - b.Property("Description") - .HasColumnType("text"); - - b.HasKey("Id"); - - b.ToTable("TestModels"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => - { - b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) - .WithMany() - .HasForeignKey("RoleId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => - { - b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) - .WithMany() - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => - { - b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) - .WithMany() - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", 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", b => - { - b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) - .WithMany() - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.NoSharding/Migrations/20220610041036_initialCreate.cs b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.NoSharding/Migrations/20220610041036_initialCreate.cs deleted file mode 100644 index f5c170b0..00000000 --- a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.NoSharding/Migrations/20220610041036_initialCreate.cs +++ /dev/null @@ -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(type: "text", nullable: false), - Name = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), - NormalizedName = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), - ConcurrencyStamp = table.Column(type: "text", nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_AspNetRoles", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "AspNetUsers", - columns: table => new - { - Id = table.Column(type: "text", nullable: false), - UserName = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), - NormalizedUserName = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), - Email = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), - NormalizedEmail = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), - EmailConfirmed = table.Column(type: "boolean", nullable: false), - PasswordHash = table.Column(type: "text", nullable: true), - SecurityStamp = table.Column(type: "text", nullable: true), - ConcurrencyStamp = table.Column(type: "text", nullable: true), - PhoneNumber = table.Column(type: "text", nullable: true), - PhoneNumberConfirmed = table.Column(type: "boolean", nullable: false), - TwoFactorEnabled = table.Column(type: "boolean", nullable: false), - LockoutEnd = table.Column(type: "timestamp with time zone", nullable: true), - LockoutEnabled = table.Column(type: "boolean", nullable: false), - AccessFailedCount = table.Column(type: "integer", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_AspNetUsers", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "TestModels", - columns: table => new - { - Id = table.Column(type: "uuid", nullable: false), - Content = table.Column(type: "text", nullable: true), - Description = table.Column(type: "text", nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_TestModels", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "AspNetRoleClaims", - columns: table => new - { - Id = table.Column(type: "integer", nullable: false) - .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), - RoleId = table.Column(type: "text", nullable: false), - ClaimType = table.Column(type: "text", nullable: true), - ClaimValue = table.Column(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(type: "integer", nullable: false) - .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), - UserId = table.Column(type: "text", nullable: false), - ClaimType = table.Column(type: "text", nullable: true), - ClaimValue = table.Column(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(type: "character varying(128)", maxLength: 128, nullable: false), - ProviderKey = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), - ProviderDisplayName = table.Column(type: "text", nullable: true), - UserId = table.Column(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(type: "text", nullable: false), - RoleId = table.Column(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(type: "text", nullable: false), - LoginProvider = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), - Name = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), - Value = table.Column(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"); - } - } -} diff --git a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.NoSharding/Migrations/20220610090653_TestModel_Add_CreationTime.cs b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.NoSharding/Migrations/20220610090653_TestModel_Add_CreationTime.cs deleted file mode 100644 index 97402a11..00000000 --- a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.NoSharding/Migrations/20220610090653_TestModel_Add_CreationTime.cs +++ /dev/null @@ -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( - 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"); - } - } -} diff --git a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.NoSharding/WebApplication1.Migrations.NoSharding.csproj b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.NoSharding/WebApplication1.Migrations.NoSharding.csproj deleted file mode 100644 index e9d3885d..00000000 --- a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.NoSharding/WebApplication1.Migrations.NoSharding.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - net6.0 - enable - enable - - - - - - - - - - - diff --git a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.NoSharding/Migrations/20220610090653_TestModel_Add_CreationTime.Designer.cs b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Sharding/Migrations/20220712092732_TestModel_Id_RenameTo_Id2.Designer.cs similarity index 81% rename from samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.NoSharding/Migrations/20220610090653_TestModel_Add_CreationTime.Designer.cs rename to samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Sharding/Migrations/20220712092732_TestModel_Id_RenameTo_Id2.Designer.cs index 7a2687e7..0b0e0808 100644 --- a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.NoSharding/Migrations/20220610090653_TestModel_Add_CreationTime.Designer.cs +++ b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Sharding/Migrations/20220712092732_TestModel_Id_RenameTo_Id2.Designer.cs @@ -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("Id") + .HasColumnType("uuid"); + + b.Property("Name") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("GuidShardingTables"); + }); + + modelBuilder.Entity("WebApplication1.Data.Models.Order", b => { b.Property("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); + b.Property("Name") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("WebApplication1.Data.Models.Student", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Name") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Students"); + }); + + modelBuilder.Entity("WebApplication1.Data.Models.TestModel", b => + { + b.Property("Id2") + .HasColumnType("uuid"); + + b.Property("AfterShardingDb") + .HasColumnType("text"); + b.Property("Content") .HasColumnType("text"); @@ -239,11 +284,31 @@ namespace WebApplication1.Migrations.NoSharding.Migrations b.Property("Description") .HasColumnType("text"); - b.HasKey("Id"); + b.Property("TestNewField") + .HasColumnType("text"); + + b.HasKey("Id2"); b.ToTable("TestModels"); }); + modelBuilder.Entity("WebApplication1.Data.Models.TestModelKey", b => + { + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("Key") + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("CreationDate") + .HasColumnType("timestamp without time zone"); + + b.HasKey("Id", "Key"); + + b.ToTable("TestModelKeys"); + }); + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) diff --git a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Sharding/Migrations/20220712092732_TestModel_Id_RenameTo_Id2.cs b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Sharding/Migrations/20220712092732_TestModel_Id_RenameTo_Id2.cs new file mode 100644 index 00000000..4e1e64df --- /dev/null +++ b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Sharding/Migrations/20220712092732_TestModel_Id_RenameTo_Id2.cs @@ -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( + name: "CreationTime", + table: "TestModels", + type: "timestamp without time zone", + nullable: false, + oldClrType: typeof(DateTime), + oldType: "timestamp with time zone"); + + migrationBuilder.AlterColumn( + name: "CreationDate", + table: "TestModelKeys", + type: "timestamp without time zone", + nullable: false, + oldClrType: typeof(DateTime), + oldType: "timestamp with time zone"); + + migrationBuilder.AlterColumn( + name: "Name", + table: "AspNetUserTokens", + type: "character varying(128)", + maxLength: 128, + nullable: false, + oldClrType: typeof(string), + oldType: "text"); + + migrationBuilder.AlterColumn( + name: "LoginProvider", + table: "AspNetUserTokens", + type: "character varying(128)", + maxLength: 128, + nullable: false, + oldClrType: typeof(string), + oldType: "text"); + + migrationBuilder.AlterColumn( + name: "ProviderKey", + table: "AspNetUserLogins", + type: "character varying(128)", + maxLength: 128, + nullable: false, + oldClrType: typeof(string), + oldType: "text"); + + migrationBuilder.AlterColumn( + 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( + name: "CreationTime", + table: "TestModels", + type: "timestamp with time zone", + nullable: false, + oldClrType: typeof(DateTime), + oldType: "timestamp without time zone"); + + migrationBuilder.AlterColumn( + name: "CreationDate", + table: "TestModelKeys", + type: "timestamp with time zone", + nullable: false, + oldClrType: typeof(DateTime), + oldType: "timestamp without time zone"); + + migrationBuilder.AlterColumn( + name: "Name", + table: "AspNetUserTokens", + type: "text", + nullable: false, + oldClrType: typeof(string), + oldType: "character varying(128)", + oldMaxLength: 128); + + migrationBuilder.AlterColumn( + name: "LoginProvider", + table: "AspNetUserTokens", + type: "text", + nullable: false, + oldClrType: typeof(string), + oldType: "character varying(128)", + oldMaxLength: 128); + + migrationBuilder.AlterColumn( + name: "ProviderKey", + table: "AspNetUserLogins", + type: "text", + nullable: false, + oldClrType: typeof(string), + oldType: "character varying(128)", + oldMaxLength: 128); + + migrationBuilder.AlterColumn( + name: "LoginProvider", + table: "AspNetUserLogins", + type: "text", + nullable: false, + oldClrType: typeof(string), + oldType: "character varying(128)", + oldMaxLength: 128); + } + } +} diff --git a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.NoSharding/Migrations/ApplicationDbContextModelSnapshot.cs b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Sharding/Migrations/20220712093155_TestModel_Add_IntId.Designer.cs similarity index 79% rename from samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.NoSharding/Migrations/ApplicationDbContextModelSnapshot.cs rename to samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Sharding/Migrations/20220712093155_TestModel_Add_IntId.Designer.cs index 8f5f9b3c..a38fc625 100644 --- a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.NoSharding/Migrations/ApplicationDbContextModelSnapshot.cs +++ b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Sharding/Migrations/20220712093155_TestModel_Add_IntId.Designer.cs @@ -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("Id") + .HasColumnType("uuid"); + + b.Property("Name") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("GuidShardingTables"); + }); + + modelBuilder.Entity("WebApplication1.Data.Models.Order", b => { b.Property("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); + b.Property("Name") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("WebApplication1.Data.Models.Student", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Name") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Students"); + }); + + modelBuilder.Entity("WebApplication1.Data.Models.TestModel", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AfterShardingDb") + .HasColumnType("text"); + b.Property("Content") .HasColumnType("text"); @@ -237,11 +287,31 @@ namespace WebApplication1.Migrations.NoSharding.Migrations b.Property("Description") .HasColumnType("text"); + b.Property("TestNewField") + .HasColumnType("text"); + b.HasKey("Id"); b.ToTable("TestModels"); }); + modelBuilder.Entity("WebApplication1.Data.Models.TestModelKey", b => + { + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("Key") + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("CreationDate") + .HasColumnType("timestamp without time zone"); + + b.HasKey("Id", "Key"); + + b.ToTable("TestModelKeys"); + }); + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) diff --git a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Sharding/Migrations/20220712093155_TestModel_Add_IntId.cs b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Sharding/Migrations/20220712093155_TestModel_Add_IntId.cs new file mode 100644 index 00000000..2b8af3a9 --- /dev/null +++ b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Sharding/Migrations/20220712093155_TestModel_Add_IntId.cs @@ -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( + 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( + 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"); + } + } +} diff --git a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Sharding/Migrations/AbstaractShardingDbContextModelSnapshot.cs b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Sharding/Migrations/AbstaractShardingDbContextModelSnapshot.cs index 35f74814..423affea 100644 --- a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Sharding/Migrations/AbstaractShardingDbContextModelSnapshot.cs +++ b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Sharding/Migrations/AbstaractShardingDbContextModelSnapshot.cs @@ -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", b => { b.Property("LoginProvider") - .HasColumnType("text"); + .HasMaxLength(128) + .HasColumnType("character varying(128)"); b.Property("ProviderKey") - .HasColumnType("text"); + .HasMaxLength(128) + .HasColumnType("character varying(128)"); b.Property("ProviderDisplayName") .HasColumnType("text"); @@ -205,10 +207,12 @@ namespace WebApplication1.Migrations.Sharding.Migrations .HasColumnType("text"); b.Property("LoginProvider") - .HasColumnType("text"); + .HasMaxLength(128) + .HasColumnType("character varying(128)"); b.Property("Name") - .HasColumnType("text"); + .HasMaxLength(128) + .HasColumnType("character varying(128)"); b.Property("Value") .HasColumnType("text"); @@ -263,9 +267,11 @@ namespace WebApplication1.Migrations.Sharding.Migrations modelBuilder.Entity("WebApplication1.Data.Models.TestModel", b => { - b.Property("Id") + b.Property("Id") .ValueGeneratedOnAdd() - .HasColumnType("uuid"); + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); b.Property("AfterShardingDb") .HasColumnType("text"); @@ -274,7 +280,7 @@ namespace WebApplication1.Migrations.Sharding.Migrations .HasColumnType("text"); b.Property("CreationTime") - .HasColumnType("timestamp with time zone"); + .HasColumnType("timestamp without time zone"); b.Property("Description") .HasColumnType("text"); @@ -297,7 +303,7 @@ namespace WebApplication1.Migrations.Sharding.Migrations .HasColumnType("character varying(36)"); b.Property("CreationDate") - .HasColumnType("timestamp with time zone"); + .HasColumnType("timestamp without time zone"); b.HasKey("Id", "Key"); diff --git a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Sharding/WebApplication1.Migrations.Sharding.csproj b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Sharding/WebApplication1.Migrations.Sharding.csproj index a6ec964d..26168e99 100644 --- a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Sharding/WebApplication1.Migrations.Sharding.csproj +++ b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Sharding/WebApplication1.Migrations.Sharding.csproj @@ -8,7 +8,7 @@ - + diff --git a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Tool/Program.cs b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Tool/Program.cs deleted file mode 100644 index 3b638668..00000000 --- a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Tool/Program.cs +++ /dev/null @@ -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!"); diff --git a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Tool/ShardingDesignTimeDbContextFactory.cs b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Tool/ShardingDesignTimeDbContextFactory.cs deleted file mode 100644 index 81b9f2ab..00000000 --- a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Tool/ShardingDesignTimeDbContextFactory.cs +++ /dev/null @@ -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 - { - - const string migrationsAssemblyName = "WebApplication1.Migrations.Sharding"; - - static ShardingDesignTimeDbContextFactory() - { - var services = new ServiceCollection(); - - services.AddShardingDbContext() - .AddEntityConfig(o => - { - o.CreateDataBaseOnlyOnStart = true; // 启动时创建数据库 - o.CreateShardingTableOnStart = false; // 如果您使用code-first建议选择false - o.EnsureCreatedWithOutShardingTable = false; // 如果您使用code-first建议修改为fsle - o.IgnoreCreateTableError = false; // 如果不忽略就会输出warning的日志 - - //添加分库路由 - o.AddShardingDataSourceRoute(); - - //添加分表路由 - o.AddShardingTableRoute(); - o.AddShardingTableRoute(); - o.AddShardingTableRoute(); - }) - .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()); - op.AddDefaultDataSource("ds0", "server=127.0.0.1;port=5432;uid=postgres;pwd=3#SanJing;database=shardingCoreDemo;"); - - op.UseShellDbContextConfigure(builder => - { - builder.ReplaceService>() - //.ReplaceService();//如果需要移除外键可以添加这个 - ; - }); - - }).EnsureConfig(); - - services.AddLogging(); - var buildServiceProvider = services.BuildServiceProvider(); - ShardingContainer.SetServices(buildServiceProvider); - ShardingContainer.GetService().Start(); - - buildServiceProvider.InitialDynamicVirtualDataSource(); - } - - public AbstaractShardingDbContext CreateDbContext(string[] args) - { - return ShardingContainer.GetService(); - } - } - -} diff --git a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Tool/TestModelKey_Create.sql b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Tool/TestModelKey_Create.sql deleted file mode 100644 index d3532601..00000000 --- a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Tool/TestModelKey_Create.sql +++ /dev/null @@ -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; - diff --git a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Tool/WebApplication1.Migrations.Tool.csproj b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Tool/WebApplication1.Migrations.Tool.csproj deleted file mode 100644 index 179f660d..00000000 --- a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Tool/WebApplication1.Migrations.Tool.csproj +++ /dev/null @@ -1,24 +0,0 @@ - - - - Exe - net6.0 - enable - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - \ No newline at end of file diff --git a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Tool/migrations.sql b/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Tool/migrations.sql deleted file mode 100644 index 04f1fbf8..00000000 --- a/samples/Samples.DynamicDb.Npgsql/WebApplication1.Migrations.Tool/migrations.sql +++ /dev/null @@ -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; - diff --git a/samples/Samples.DynamicDb.Npgsql/WebApplication1/Pages/BatchCreateDbKey.cshtml.cs b/samples/Samples.DynamicDb.Npgsql/WebApplication1/Pages/BatchCreateDbKey.cshtml.cs index 4897df9d..5a21f98a 100644 --- a/samples/Samples.DynamicDb.Npgsql/WebApplication1/Pages/BatchCreateDbKey.cshtml.cs +++ b/samples/Samples.DynamicDb.Npgsql/WebApplication1/Pages/BatchCreateDbKey.cshtml.cs @@ -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>(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("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>(AppContext.BaseDirectory, TestModelVirtualDataSourceRoute.ConfigFileName); - dblist.AddRange(keyList); - JsonFileHelper.Save(AppContext.BaseDirectory, TestModelVirtualDataSourceRoute.ConfigFileName, dblist); + db.Database.Migrate(); return RedirectToPage("DbKeyMan"); diff --git a/samples/Samples.DynamicDb.Npgsql/WebApplication1/Pages/CreateDbKey.cshtml.cs b/samples/Samples.DynamicDb.Npgsql/WebApplication1/Pages/CreateDbKey.cshtml.cs index ef81a08b..2280bc9b 100644 --- a/samples/Samples.DynamicDb.Npgsql/WebApplication1/Pages/CreateDbKey.cshtml.cs +++ b/samples/Samples.DynamicDb.Npgsql/WebApplication1/Pages/CreateDbKey.cshtml.cs @@ -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("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"); } diff --git a/samples/Samples.DynamicDb.Npgsql/WebApplication1/Program.cs b/samples/Samples.DynamicDb.Npgsql/WebApplication1/Program.cs index ec140132..de50d725 100644 --- a/samples/Samples.DynamicDb.Npgsql/WebApplication1/Program.cs +++ b/samples/Samples.DynamicDb.Npgsql/WebApplication1/Program.cs @@ -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(options => -//{ -// options.UseNpgsql(npgConnectionString, x => x.MigrationsAssembly(migrationsAssemblyName)); -//}); +#region 注入 dbcontext services .AddShardingDbContext() - .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(); @@ -46,32 +42,52 @@ services o.AddShardingTableRoute(); o.AddShardingTableRoute(); }) - .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()); - op.AddDefaultDataSource("ds0", npgConnectionString); - //op.AddExtraDataSource(sp => new Dictionary() - //{ - // {"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>() - //.ReplaceService();//如果需要移除外键可以添加这个 + 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() + // { + // {"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>(); + }); }) - .EnsureConfig(); + .ReplaceService() + .AddShardingCore(); #endregion @@ -86,11 +102,13 @@ services.AddDatabaseDeveloperPageExceptionFilter(); var app = builder.Build(); -var shardingBootstrapper = app.Services.GetRequiredService(); -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(scope.ServiceProvider); - +watch.Stop(); +Console.WriteLine($"耗时:{watch.Elapsed.TotalMilliseconds} 毫秒"); await app.RunAsync(); diff --git a/samples/Samples.DynamicDb.Npgsql/WebApplication1/WebApplication1.csproj b/samples/Samples.DynamicDb.Npgsql/WebApplication1/WebApplication1.csproj index c65a243f..d5562b1a 100644 --- a/samples/Samples.DynamicDb.Npgsql/WebApplication1/WebApplication1.csproj +++ b/samples/Samples.DynamicDb.Npgsql/WebApplication1/WebApplication1.csproj @@ -13,7 +13,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive - + diff --git a/samples/Samples.DynamicDb.Npgsql/WebApplication1/appsettings.Development.json b/samples/Samples.DynamicDb.Npgsql/WebApplication1/appsettings.Development.json index 8983e0fc..e206c14e 100644 --- a/samples/Samples.DynamicDb.Npgsql/WebApplication1/appsettings.Development.json +++ b/samples/Samples.DynamicDb.Npgsql/WebApplication1/appsettings.Development.json @@ -1,9 +1,9 @@ { "Logging": { "LogLevel": { - "Default": "Information", + "Default": "debug", "Microsoft": "Warning", - "Microsoft.Hosting.Lifetime": "Information" + "Microsoft.Hosting.Lifetime": "debug" } } }