### Install ShardingCore packages Source: https://github.com/dotnetcore/sharding-core/blob/main/README.md Install the core package and the required database driver for Entity Framework Core. ```shell # basic package[README-zh.md](README-zh.md) PM> Install-Package ShardingCore # sqlserver driver PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer # mysql driver #PM> Install-Package Pomelo.EntityFrameworkCore.MySql # use other database driver,if efcore support ``` -------------------------------- ### Get Help Command Source: https://github.com/dotnetcore/sharding-core/blob/main/samples/Sample.Migrations/readme.md Command to access help information for Entity Framework Core. Useful for understanding available commands and options. ```powershell Get-Help about_EntityFrameworkCore ``` -------------------------------- ### Project Directory Structure Source: https://github.com/dotnetcore/sharding-core/blob/main/samples/Samples.DynamicDb.Npgsql/readme.md Overview of the directory structure for the ShardingCoreDemo project, detailing the purpose of each sub-project. ```txt ├── WebApplication1 webapp 项目 ├── WebApplication1.Data 存储数据模型和dbcontext的项目(一些公用的方法也存储在这个项目中) ├── WebApplication1.Migrations.NoSharding 未分片前的迁移程序集项目 ├── WebApplication1.Migrations.Sharding 分片后的迁移程序集项目 ├── WebApplication1.Migrations.Tool 迁移工具项目,在tool项目下可利用 ef tool 完成迁移文件的创建 ``` -------------------------------- ### Configure Virtual Table Route Source: https://github.com/dotnetcore/sharding-core/blob/main/README.md Create a route class to map data queries to specific table names based on the creation time. ```csharp //Route constructor support dependency injection,that's life time scope is `Singleton` public class OrderVirtualTableRoute:AbstractSimpleShardingMonthKeyDateTimeVirtualTableRoute { //private readonly IServiceProvider _serviceProvider; //public OrderVirtualTableRoute(IServiceProvider serviceProvider) //{ //_serviceProvider = serviceProvider; //} /// /// fixed value don't use DateTime.Now because if if application restart this value where change /// /// public override DateTime GetBeginTime() { return new DateTime(2021, 1, 1); } /// /// configure sharding property /// /// public override void Configure(EntityMetadataTableBuilder builder) { builder.ShardingProperty(o => o.CreationTime); } /// /// enable auto create table job /// /// public override bool AutoCreateTableByTime() { return true; } } ``` -------------------------------- ### Configure Sharding-Core Services Source: https://github.com/dotnetcore/sharding-core/blob/main/README.md Register sharding configuration, routing, and data sources in ConfigureServices, and optionally enable auto-table creation in Configure. ```csharp public void ConfigureServices(IServiceCollection services) { //sharding config services.AddShardingDbContext() .UseRouteConfig(op => { op.AddShardingTableRoute(); }).UseConfig(op => { op.UseShardingQuery((connStr, builder) => { //connStr is delegate input param builder.UseSqlServer(connStr); }); op.UseShardingTransaction((connection, builder) => { //connection is delegate input param builder.UseSqlServer(connection); }); //use your data base connection string op.AddDefaultDataSource(Guid.NewGuid().ToString("n"), "Data Source=localhost;Initial Catalog=EFCoreShardingTableDB;Integrated Security=True;"); }).AddShardingCore(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } //not required, enable check table missing and auto create,非必须 启动检查缺少的表并且创建 app.ApplicationServices.UseAutoTryCompensateTable(); // other configure.... } ``` -------------------------------- ### Implement Sharding DbContext Source: https://github.com/dotnetcore/sharding-core/blob/main/README.md Create a DbContext that inherits from AbstractShardingDbContext and implements IShardingTableDbContext for table splitting support. ```csharp public class MyDbContext:AbstractShardingDbContext,IShardingTableDbContext { public MyDbContext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity(entity => { entity.HasKey(o => o.Id); entity.Property(o => o.Id).IsRequired().IsUnicode(false).HasMaxLength(50); entity.Property(o=>o.Payer).IsRequired().IsUnicode(false).HasMaxLength(50); entity.Property(o => o.Area).IsRequired().IsUnicode(false).HasMaxLength(50); entity.Property(o => o.OrderStatus).HasConversion(); //really table name is Order_202101,Order_202102,Order_202103..... entity.ToTable(nameof(Order)); }); } /// /// empty implment if use sharding table /// public IRouteTail RouteTail { get; set; } } ``` -------------------------------- ### Branching Strategy Source: https://github.com/dotnetcore/sharding-core/blob/main/samples/Samples.DynamicDb.Npgsql/readme.md Explanation of the branching strategy for the ShardingCoreDemo project, differentiating between the master branch for static sharding and a separate branch for dynamic sharding. ```txt ├── master 主分支,从一个正常的ef codefirst 项目,到使用 sharingcore 分库(静态)分表 的过程 ├── 动态分库 动态分库分支,由于动态分库会移除掉静态分库的部分内容,所以单独分支存在,在完成静态分库后创建 ``` -------------------------------- ### EFCore.Sharding Migration Commands Source: https://github.com/dotnetcore/sharding-core/blob/main/samples/Sample.Migrations/readme.md Commonly used Package Manager Console commands for managing EFCore.Sharding migrations. These commands help in creating, scripting, and applying database schema changes. ```powershell Add-Migration InitialCreate (Add-Migration EFCoreSharding -Context DefaultShardingTableDbContext -OutputDir Migrations\ShardingMigrations) ``` ```powershell Add-Migration [NewMigration] -Context CustomContext ``` ```powershell Remove-Migration -Context CustomContext ``` ```powershell Script-Migration -Context CustomContext -from:[TargetMigration] ( Script-Migration -Context DefaultShardingTableDbContext)用于生产环境 ``` ```powershell Update-Database -Context CustomContext (Update-Database -Context DefaultShardingTableDbContext -Verbose) ``` ```powershell Add-Migration InitialCreate ``` ```powershell Add-Migration InitialCreate –IgnoreChanges ``` ```powershell Add-Migration [NewMigration] ``` ```powershell Remove-Migration ``` ```powershell Update-Database ``` ```powershell Update-Database -Verbose ``` ```powershell Update-Database -TargetMigration:AddSomething ``` ```powershell Update-Database –TargetMigration: $InitialDatabase ``` ```powershell Script-Migration ``` ```powershell Script-Migration -Context BusinessDbContext -from InitialCreate -to AddInspectorWorkShift ``` -------------------------------- ### Scaffold DbContext Command Source: https://github.com/dotnetcore/sharding-core/blob/main/samples/Sample.Migrations/readme.md Command to scaffold a DbContext from an existing database. Use this to generate model classes and a DbContext based on your database schema. ```powershell Scaffold-DbContext 'Data Source=.;Initial Catalog=TesbDb;Integrated Security=True;Pooling=true;' -Schemas 'PDEV' -UseDatabaseNames -DataAnnotations -Force Microsoft.EntityFrameworkCore.SqlServer ``` -------------------------------- ### Custom DbContext Factory for Sharding Source: https://github.com/dotnetcore/sharding-core/blob/main/samples/Sample.Migrations/readme.md Implementation of IDesignTimeDbContextFactory for EFCore.Sharding. This factory configures the DbContext with sharding capabilities, including automatic table routing and sharding SQL generator. ```csharp //创建对应的IDesignTimeDbContextFactory并且设置启动时不建表启动时不库 `.ReplaceService>()` 添加自动分表迁移 public class DefaultDesignTimeDbContextFactory: IDesignTimeDbContextFactory { static DefaultDesignTimeDbContextFactory() { var services = new ServiceCollection(); services.AddShardingDbContext( o => o.UseSqlServer("Data Source=localhost;Initial Catalog=ShardingCoreDBMigration;Integrated Security=True;") .ReplaceService>() ).Begin(o => { o.CreateShardingTableOnStart = false; o.EnsureCreatedWithOutShardingTable = false; o.AutoTrackEntity = true; }) .AddShardingQuery((conStr, builder) => builder.UseSqlServer(conStr) .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)) .AddShardingTransaction((connection, builder) => builder.UseSqlServer(connection)) .AddDefaultDataSource("ds0", "Data Source=localhost;Initial Catalog=ShardingCoreDBMigration;Integrated Security=True;") .AddShardingTableRoute(o => { o.AddShardingTableRoute(); o.AddShardingTableRoute(); }).End(); services.AddLogging(); var buildServiceProvider = services.BuildServiceProvider(); ShardingContainer.SetServices(buildServiceProvider); new ShardingBootstrapper(buildServiceProvider).Start(); } public DefaultShardingTableDbContext CreateDbContext(string[] args) { return ShardingContainer.GetService(); } } ``` -------------------------------- ### Define the Order entity Source: https://github.com/dotnetcore/sharding-core/blob/main/README.md Define the entity class and status enum to be used for sharding. ```csharp /// /// order table /// public class Order { /// /// order Id /// public string Id { get; set; } /// /// payer id /// public string Payer { get; set; } /// /// pay money cent /// public long Money { get; set; } /// /// area /// public string Area { get; set; } /// /// order status /// public OrderStatusEnum OrderStatus { get; set; } /// /// CreationTime /// public DateTime CreationTime { get; set; } } public enum OrderStatusEnum { NoPay=1, Paying=2, Payed=3, PayFail=4 } ``` -------------------------------- ### Perform Database Operations with Sharding Source: https://github.com/dotnetcore/sharding-core/blob/main/README.md Inject the sharded DbContext into a controller to execute standard EF Core operations. ```csharp [Route("api/[controller]")] public class ValuesController : Controller { private readonly MyDbContext _myDbContext; public ValuesController(MyDbContext myDbContext) { _myDbContext = myDbContext; } [HttpGet] public async Task Get() { //_myDbContext.Add(order); //_myDbContext.Udpate(order); //_myDbContext.Remove(order); //_myDbContext.SaveChanges(); var order = await _myDbContext.Set().FirstOrDefaultAsync(o => o.Id == "2"); return OK(order) } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.