This commit is contained in:
xuejmnet 2021-08-20 23:10:34 +08:00
parent 8f3b6b3aad
commit 310dca2c17
16 changed files with 1014 additions and 1015 deletions

222
README.md
View File

@ -1,16 +1,28 @@
<h1 align="center"> ShardingCore </h1> <h1 align="center"> ShardingCore </h1>
`ShardingCore` 是一个支持efcore 2.x 3.x 5.x的一个分库分表的一个简易扩展,针对dbContext实现了无感知开发,针对之前x.0.0.x版本目前在之前的分表功能上支持了分库功能。 `ShardingCore`是什么简单来说我认为他是目前最完美的efcore下的分表组件,支持所有的efcore支持的数据库(原则上),针对dbContext进行plus升级实现了无感知开发。
目前x.1.0.x的所有版本都支持分库分表,在使用程度上极大的降低了代码侵入性保证开发时候的无感知使用。该框架是基于efcore的虽然没有像sharding-jdbc一样支持任意jdbc的实现但是针对efcore下的框架基本上都适用, 在使用程度上极大的降低了代码侵入性保证开发时候的无感知使用(和efcore原生dbcontext一样)。
该框架在分表数据下使用的而架构是流式聚合可以保证内存的稳定,而非内存迭代。
但是针对efcore下的框架基本上都适用,你以为这就完了吗shardingcore我可以说完美支持abp并且无侵入性。
最后如果喜欢本项目的话或者本项目对您有帮助的话麻烦[点我star github 地址](https://github.com/xuejmnet/sharding-core) ,也欢迎各位.neter交流。 最后如果喜欢本项目的话或者本项目对您有帮助的话麻烦[点我star github 地址](https://github.com/xuejmnet/sharding-core) ,也欢迎各位.neter交流。
### 依赖 ### 依赖
Release | EF Core | .NET Standard | .NET (Core) | Sql Server | [Pomelo.EntityFrameworkCore.MySql](https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql) Release | EF Core | .NET Standard | .NET (Core)
--- | --- | --- | --- | --- | --- --- | --- | --- | ---
[5.1.x.x](https://www.nuget.org/packages/ShardingCore/5.1.0.21) | >= 5.0.x | 2.1 | 3.0+ | >= 2012 | 5.0.0 [5.2.x.x](https://www.nuget.org/packages/ShardingCore/5.12.0.03) | >= 5.0.x | 2.1 | 3.0+
[3.1.x.x](https://www.nuget.org/packages/ShardingCore/3.1.0.21) | 3.1.10 | 2.0 | 2.0+ | >= 2012 | 3.2.4 [3.2.x.x](https://www.nuget.org/packages/ShardingCore/3.2.0.03) | 3.1.10 | 2.0 | 2.0+
[2.1.x.x](https://www.nuget.org/packages/ShardingCore/2.1.0.21) | 2.2.6 | 2.0 | 2.0+ | >= 2008 | 2.2.6 [2.2.x.x](https://www.nuget.org/packages/ShardingCore/2.2.0.03) | 2.2.6 | 2.0 | 2.0+
### 数据库支持
数据库 | 是否支持 | 支持情况
--- | --- | ---
SqlServer | 是 | 80%近乎完美
MySql |支持 | 未测试
PostgreSql | 支持 | 未测试
SQLite | 支持 | 未测试
Oracle | 支持 | 未测试
其他 | 支持(只要efcore支持) | 未测试
- [开始](#开始) - [开始](#开始)
@ -47,6 +59,7 @@ Release | EF Core | .NET Standard | .NET (Core) | Sql Server | [Pomelo.EntityFr
该库的简介目前仅使用该库无法或者说难以实现自动建表,但是只需要配合定时任务该库即可完成24小时无人看管自动管理。该库提供了 [IShardingTableCreator](https://github.com/xuejmnet/sharding-core/blob/main/src/ShardingCore/TableCreator/IShardingTableCreator.cs) 该库的简介目前仅使用该库无法或者说难以实现自动建表,但是只需要配合定时任务该库即可完成24小时无人看管自动管理。该库提供了 [IShardingTableCreator](https://github.com/xuejmnet/sharding-core/blob/main/src/ShardingCore/TableCreator/IShardingTableCreator.cs)
作为建表的依赖,如果需要可以参考 [按天自动建表](https://github.com/xuejmnet/sharding-core/tree/main/samples/Samples.AutoByDate.SqlServer) 作为建表的依赖,如果需要可以参考 [按天自动建表](https://github.com/xuejmnet/sharding-core/tree/main/samples/Samples.AutoByDate.SqlServer)
目前所有的demo可以参考 项目源码里面的Sample.SqlServer
## 概念 ## 概念
@ -66,21 +79,22 @@ Release | EF Core | .NET Standard | .NET (Core) | Sql Server | [Pomelo.EntityFr
## 优点 ## 优点
- [支持自定义分库、分表规则] - [支持自定义分表规则]
- [支持任意类型分表key] - [支持任意类型分表key]
- [针对iqueryable的扩展方便使用] - [对dbcontext扩展近乎完美]
- [支持分表下的连表] ```join,group by,max,count,min,avg,sum``` - [支持分表下的连表] ```join,group by,max,count,min,avg,sum```
- [支持针对批处理的使用] ``` BulkInsert、BulkUpdate、BulkDelete```支持efcore的扩展生态 - [支持针对批处理的使用] [EFCore.BulkExtensions](https://github.com/borisdj/EFCore.BulkExtensions) ...支持efcore的扩展生态
- [提供多种默认分表规则路由] 按时间按取模 - [提供多种默认分表规则路由] 按时间,按取模 可自定义
- [针对分页进行优化] 大页数跳转支持低内存流式处理 - [针对分页进行优化] 大页数跳转支持低内存流式处理
## 缺点 ## 缺点
- [暂不支持分库]
- [消耗连接]出现分表与分表对象进行join如果条件没法索引到具体表会生成```笛卡尔积```导致连接数爆炸,后期会进行针对该情况的配置 - [消耗连接]出现分表与分表对象进行join如果条件没法索引到具体表会生成```笛卡尔积```导致连接数爆炸,后期会进行针对该情况的配置
- [该库比较年轻] 可能会有一系列bug或者单元测试不到位的情况,但是只要你在群里或者提了issues我会尽快解决 - [该库比较年轻] 可能会有一系列bug或者单元测试不到位的情况,但是只要你在群里或者提了issues我会尽快解决
## 安装 ## 安装
```xml ```xml
<PackageReference Include="ShardingCore.SqlServer" Version="5.1.0.9" /> <PackageReference Include="ShardingCore" Version="5.2.0.03" />
``` ```
## 配置 ## 配置
@ -122,23 +136,69 @@ Release | EF Core | .NET Standard | .NET (Core) | Sql Server | [Pomelo.EntityFr
} }
} }
``` ```
创建DbContext必须继承IShardingTableDbContext
```c#
public class DefaultTableDbContext: DbContext,IShardingTableDbContext
{
public DefaultTableDbContext(DbContextOptions<DefaultTableDbContext> options) :base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfiguration(new SysUserModMap());
modelBuilder.ApplyConfiguration(new SysTestMap());
}
public string ModelChangeKey { get; set; }
}
```
创建分表DbContext必须继承AbstractShardingDbContext<DefaultTableDbContext>其中DefaultTableDbContext是你刚才建立的就是如果你分表了你真正获取对象是通过哪个dbcontext
```c#
public class DefaultShardingDbContext:AbstractShardingDbContext<DefaultTableDbContext>
{
public DefaultShardingDbContext(DbContextOptions<DefaultShardingDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfiguration(new SysUserModMap());
modelBuilder.ApplyConfiguration(new SysTestMap());
}
public override Type ShardingDbContextType => this.GetType();
}
```
`Startup.cs` 下的 `ConfigureServices(IServiceCollection services)` `Startup.cs` 下的 `ConfigureServices(IServiceCollection services)`
```c# ```c#
services.AddShardingSqlServer(o => public void ConfigureServices(IServiceCollection services)
{
//如果是development就判断并且新建数据库如果不存在的话(ishardingentity不会被创建)
o.EnsureCreatedWithOutShardingTable = true;
//ishardingentity表是否需要在启动时创建(如果已创建可以选择不创建)
o.CreateShardingTableOnStart = true;
//添加分库dbcontext
o.AddShardingDbContextWithShardingTable<DefaultTableDbContext>("conn1", "Data Source=localhost;Initial Catalog=ShardingCoreDB;Integrated Security=True", dbConfig =>
{ {
//添加分表规则 services.AddControllers();
dbConfig.AddShardingTableRoute<SysUserModVirtualTableRoute>(); //services.AddDbContext<DefaultTableDbContext>(o => o.UseSqlServer("Data Source=localhost;Initial Catalog=ShardingCoreDBxx3;Integrated Security=True"));
});
}); //添加shardingdbcontext support life scope
services.AddShardingDbContext<DefaultShardingDbContext, DefaultTableDbContext>(o => o.UseSqlServer("Data Source=localhost;Initial Catalog=ShardingCoreDBxx2;Integrated Security=True;MultipleActiveResultSets=True;")
,op =>
{
op.EnsureCreatedWithOutShardingTable = true;
op.CreateShardingTableOnStart = true;
op.UseShardingDbContextOptions((connection, builder) => builder.UseSqlServer(connection).UseLoggerFactory(efLogger));
op.AddShardingTableRoute<SysUserModVirtualTableRoute>();
});
}
``` ```
`Startup.cs` 下的 ` Configure(IApplicationBuilder app, IWebHostEnvironment env)` 你也可以自行封装[app.UseShardingCore()](https://github.com/xuejmnet/sharding-core/blob/main/samples/Sample.SqlServer/DIExtension.cs) `Startup.cs` 下的 ` Configure(IApplicationBuilder app, IWebHostEnvironment env)` 你也可以自行封装[app.UseShardingCore()](https://github.com/xuejmnet/sharding-core/blob/main/samples/Sample.SqlServer/DIExtension.cs)
@ -152,31 +212,31 @@ Release | EF Core | .NET Standard | .NET (Core) | Sql Server | [Pomelo.EntityFr
## 使用 ## 使用
```c# ```c#
private readonly IVirtualDbContext _virtualDbContext; private readonly DefaultShardingDbContext _defaultShardingDbContext;
public ctor(IVirtualDbContext virtualDbContext) public ctor(DefaultShardingDbContext defaultShardingDbContext)
{ {
_virtualDbContext = virtualDbContext; _defaultShardingDbContext = defaultShardingDbContext;
} }
public async Task ToList_All() public async Task ToList_All()
{ {
//查询list集合 //查询list集合
var all=await _virtualDbContext.Set<SysUserMod>().ToShardingListAsync(); var all=await _defaultShardingDbContext.Set<SysUserMod>().ToListAsync();
//链接查询 //链接查询
var list = await (from u in _virtualDbContext.Set<SysUserMod>() var list = await (from u in _defaultShardingDbContext.Set<SysUserMod>()
join salary in _virtualDbContext.Set<SysUserSalary>() join salary in _defaultShardingDbContext.Set<SysUserSalary>()
on u.Id equals salary.UserId on u.Id equals salary.UserId
select new select new
{ {
Salary = salary.Salary, Salary = salary.Salary,
DateOfMonth = salary.DateOfMonth, DateOfMonth = salary.DateOfMonth,
Name = u.Name Name = u.Name
}).ToShardingListAsync(); }).ToListAsync();
//聚合查询 //聚合查询
var ids = new[] {"200", "300"}; var ids = new[] {"200", "300"};
var dateOfMonths = new[] {202111, 202110}; var dateOfMonths = new[] {202111, 202110};
var group = await (from u in _virtualDbContext.Set<SysUserSalary>() var group = await (from u in _defaultShardingDbContext.Set<SysUserSalary>()
.Where(o => ids.Contains(o.UserId) && dateOfMonths.Contains(o.DateOfMonth)) .Where(o => ids.Contains(o.UserId) && dateOfMonths.Contains(o.DateOfMonth))
group u by new group u by new
{ {
@ -191,24 +251,26 @@ Release | EF Core | .NET Standard | .NET (Core) | Sql Server | [Pomelo.EntityFr
AvgSalary = g.Average(o => o.Salary), AvgSalary = g.Average(o => o.Salary),
MinSalary = g.Min(o => o.Salary), MinSalary = g.Min(o => o.Salary),
MaxSalary = g.Max(o => o.Salary) MaxSalary = g.Max(o => o.Salary)
}).ToShardingListAsync(); }).ToListAsync();
} }
``` ```
更多操作可以参考单元测试 更多操作可以参考单元测试
## Api ## Api
方法 | Method | [SqlServer Unit Test](https://github.com/xuejmnet/sharding-core/blob/main/test/ShardingCore.Test50/ShardingTest.cs) | [MySql Unit Test](https://github.com/xuejmnet/sharding-core/blob/main/test/ShardingCore.Test50.MySql/ShardingTest.cs) 方法 | Method | [Unit Test](https://github.com/xuejmnet/sharding-core/blob/main/test/ShardingCore.Test50/ShardingTest.cs)
--- |--- |--- |--- --- |--- |---
获取集合 |ToShardingListAsync |yes |yes 获取集合 |ToListAsync |yes
第一条 |ShardingFirstOrDefaultAsync |yes |yes 第一条 |FirstOrDefaultAsync |yes
最大 |ShardingMaxAsync |yes |yes 最大 |MaxAsync |yes
最小 |ShardingMinAsync |yes |yes 最小 |MinAsync |yes
是否存在 |ShardingAnyAsync |yes |yes 是否存在 |AnyAsync |yes
分页 |ToShardingPageResultAsync |yes |yes 数目 |CountAsync |yes
数目 |ShardingCountAsync |yes |yes 数目 |LongCountAsync |yes
求和 |ShardingSumAsync |yes |yes 求和 |SumAsync |yes
分组 |ShardingGroupByAsync |yes |yes 平均 |AverageAsync |yes
包含 |ContainsAsync |yes
分组 |GroupByAsync |yes
## 默认路由 ## 默认路由
@ -233,32 +295,11 @@ AbstractSimpleShardingYearKeyLongVirtualTableRoute |按时间戳 |yyyy | `>,>=,<
批量操作将对应的dbcontext和数据进行分离由用户自己选择第三方框架比如zzz进行批量操作或者batchextension 批量操作将对应的dbcontext和数据进行分离由用户自己选择第三方框架比如zzz进行批量操作或者batchextension
```c# ```c#
virtualDbContext.BulkInsert<SysUserMod>(new List<SysUserMod>()) 后期支持
.BatchGroups.ForEach(pair =>
{
///zzz or other
pair.Key.BlukInsert(pair.Value);
});
var shardingBatchUpdateEntry = virtualDbContext.BulkUpdate<SysUserMod>(o => o.Id == "1", o => new SysUserMod()
{
Name = "name_01"
});
shardingBatchUpdateEntry.DbContexts.ForEach(context =>
{
//zzz or other
context.Where(shardingBatchUpdateEntry.Where).Update(shardingBatchUpdateEntry.UpdateExp);
});
``` ```
## 手动路由 ## 手动路由
```c# ```c#
var shardingQueryable = _virtualDbContext.Set<SysUserMod>().AsSharding(); 后续支出
//禁用自动路由
shardingQueryable.DisableAutoRouteParse();
//添加路由直接查询尾巴0的表
shardingQueryable.AddManualRoute<SysUserMod>("0");
//添加路由针对该条件的路由
shardingQueryable.AddManualRoute<SysUserMod>(o=>o.Id=="100");
var list=await shardingQueryable.ToListAsync();
``` ```
## 自动建表 ## 自动建表
@ -267,55 +308,32 @@ context.Where(shardingBatchUpdateEntry.Where).Update(shardingBatchUpdateEntry.Up
## 事务 ## 事务
默认savechanges支持事务如果需要where.update需要手动开启事务 默认savechanges支持事务如果需要where.update需要手动开启事务
```c# ```c#
1.
_virtualDbContext.BeginTransaction(); await _defaultShardingDbContext.SaveChangesAsync();
var shardingBatchUpdateEntry = _virtualDbContext.BulkUpdate<SysUserMod>(o=>o.Id=="123",o=>new SysUserMod() 2.
{ var tran=_defaultShardingDbContext.BeginTransaction();
Name = "name_modify" await _defaultShardingDbContext.SaveChangesAsync();
}); tran.commit()
foreach (var dbContext in shardingBatchUpdateEntry.DbContexts)
{
//zzz or other batch
}
await _virtualDbContext.SaveChangesAsync();
``` ```
# 注意事项 # 注意事项
该库的IVirtualDbContext.Set<T>使用asnotracking所以基本不支持跟踪,目前框架采用AppDomain.CurrentDomain.GetAssemblies(); 该库的追踪是基于adonet的MARS(MultipleActiveResultSets=True;)所以基本不支持该特性的无法支持完美追踪
,目前框架采用AppDomain.CurrentDomain.GetAssemblies();
可能会导致程序集未被加载所以尽可能在api层加载所需要的dll 可能会导致程序集未被加载所以尽可能在api层加载所需要的dll
使用时需要注意 使用时需要注意
- 实体对象是否继承`IShardingEntity` - 实体对象是否继承`IShardingTable`
- 实体对象是否有`ShardingKey` - 实体对象是否有`ShardingKey`
- 实体对象是否映射配置已实现`IEntityTypeConfiguration<TEntity>`
- 实体对象是否已经实现了一个虚拟路由 - 实体对象是否已经实现了一个虚拟路由
- startup是否已经添加虚拟路由 - startup是否已经添加虚拟路由
- startup是否已经添加bootstrapper.start()
```c#
services.AddShardingSqlServer(o =>
{
o.ConnectionString = "";
o.AddSharding<SysUserModVirtualRoute>();
o.UseShardingCoreConfig((provider, config) =>
{
//如果是development就判断并且新建数据库如果不存在的话(ishardingentity不会被创建)
config.EnsureCreated = provider.GetService<IHostEnvironment>().IsDevelopment();
//ishardingentity表是否需要在启动时创建(如果已创建可以选择不创建)
config.CreateShardingTableOnStart = true;
});
});
```
- startup
```c#
var shardingBootstrapper = app.ApplicationServices.GetRequiredService<IShardingBootstrapper>();
shardingBootstrapper.Start();
```
# 计划 # 计划
- [提供官网如果该项目比较成功的话] - [提供官网如果该项目比较成功的话]
- [开发更完善的文档] - [开发更完善的文档]
- [支持分库] - [支持分库]
- [支持更多数据库查询] - [支持更多数据库查询完善]
# 最后 # 最后
该框架借鉴了大部分分表组件的思路,目前提供的接口都已经实现,并且支持跨表查询,基于分页查询该框架也使用了流式查询保证不会再skip大数据的时候内存会爆炸,目前这个库只是一个刚刚成型的库还有很多不完善的地方希望大家多多包涵,如果喜欢的话也希望大家给个star. 该框架借鉴了大部分分表组件的思路,目前提供的接口都已经实现,并且支持跨表查询,基于分页查询该框架也使用了流式查询保证不会再skip大数据的时候内存会爆炸,目前这个库只是一个刚刚成型的库还有很多不完善的地方希望大家多多包涵,如果喜欢的话也希望大家给个star.

View File

@ -1,74 +1,74 @@
using Microsoft.AspNetCore.Mvc; // using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging; // using Microsoft.Extensions.Logging;
using System; // using System;
using System.Collections.Generic; // using System.Collections.Generic;
using System.Linq; // using System.Linq;
using System.Threading.Tasks; // using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore; // using Microsoft.EntityFrameworkCore;
using Sample.MySql.DbContexts; // using Sample.MySql.DbContexts;
using Sample.MySql.Domain.Entities; // using Sample.MySql.Domain.Entities;
using ShardingCore.Core.PhysicTables; // using ShardingCore.Core.PhysicTables;
using ShardingCore.Core.VirtualTables; // using ShardingCore.Core.VirtualTables;
using ShardingCore.DbContexts.VirtualDbContexts; // using ShardingCore.DbContexts.VirtualDbContexts;
using ShardingCore.Extensions; // using ShardingCore.Extensions;
using ShardingCore.TableCreator; // using ShardingCore.TableCreator;
//
namespace Sample.MySql.Controllers // namespace Sample.MySql.Controllers
{ // {
[ApiController] // [ApiController]
[Route("[controller]/[action]")] // [Route("[controller]/[action]")]
public class WeatherForecastController : ControllerBase // public class WeatherForecastController : ControllerBase
{ // {
//
private readonly DefaultTableDbContext _defaultTableDbContext; // private readonly DefaultTableDbContext _defaultTableDbContext;
private readonly IVirtualTableManager _virtualTableManager; // private readonly IVirtualTableManager _virtualTableManager;
private readonly IShardingTableCreator _tableCreator; // private readonly IShardingTableCreator _tableCreator;
//
public WeatherForecastController(DefaultTableDbContext defaultTableDbContext,IVirtualTableManager virtualTableManager, IShardingTableCreator tableCreator) // public WeatherForecastController(DefaultTableDbContext defaultTableDbContext,IVirtualTableManager virtualTableManager, IShardingTableCreator tableCreator)
{ // {
_defaultTableDbContext = defaultTableDbContext; // _defaultTableDbContext = defaultTableDbContext;
_virtualTableManager = virtualTableManager; // _virtualTableManager = virtualTableManager;
_tableCreator = tableCreator; // _tableCreator = tableCreator;
} // }
//
[HttpGet] // [HttpGet]
public async Task<IActionResult> Get() // public async Task<IActionResult> Get()
{ // {
var taleAllTails = _virtualTableManager.GetVirtualTable(typeof(SysUserLogByMonth)).GetTaleAllTails(); // var taleAllTails = _virtualTableManager.GetVirtualTable(typeof(SysUserLogByMonth)).GetTaleAllTails();
//
//
var result = await _defaultTableDbContext.Set<SysTest>().AnyAsync(); // var result = await _defaultTableDbContext.Set<SysTest>().AnyAsync();
var result1 = await _defaultTableDbContext.Set<SysUserMod>().Where(o => o.Id == "2" || o.Id == "3").ToShardingListAsync(); // var result1 = await _defaultTableDbContext.Set<SysUserMod>().Where(o => o.Id == "2" || o.Id == "3").ToShardingListAsync();
var result2 = await _defaultTableDbContext.Set<SysUserLogByMonth>().Skip(1).Take(10).ToShardingListAsync(); // var result2 = await _defaultTableDbContext.Set<SysUserLogByMonth>().Skip(1).Take(10).ToShardingListAsync();
var shardingFirstOrDefaultAsync = await _defaultTableDbContext.Set<SysUserLogByMonth>().ShardingFirstOrDefaultAsync(); // var shardingFirstOrDefaultAsync = await _defaultTableDbContext.Set<SysUserLogByMonth>().ShardingFirstOrDefaultAsync();
var shardingCountAsync = await _defaultTableDbContext.Set<SysUserMod>().ShardingCountAsync(); // var shardingCountAsync = await _defaultTableDbContext.Set<SysUserMod>().ShardingCountAsync();
var shardingCountAsyn2c = _defaultTableDbContext.Set<SysUserLogByMonth>().ShardingCount(); // var shardingCountAsyn2c = _defaultTableDbContext.Set<SysUserLogByMonth>().ShardingCount();
//
return Ok(result1); // return Ok(result1);
} // }
[HttpGet] // [HttpGet]
public async Task<IActionResult> Get1() // public async Task<IActionResult> Get1()
{ // {
var allVirtualTables = _virtualTableManager.GetAllVirtualTables(); // var allVirtualTables = _virtualTableManager.GetAllVirtualTables();
foreach (var virtualTable in allVirtualTables) // foreach (var virtualTable in allVirtualTables)
{ // {
if (virtualTable.EntityType == typeof(SysUserLogByMonth)) // if (virtualTable.EntityType == typeof(SysUserLogByMonth))
{ // {
var now = DateTime.Now.Date.AddMonths(2); // var now = DateTime.Now.Date.AddMonths(2);
var tail = virtualTable.GetVirtualRoute().ShardingKeyToTail(now); // var tail = virtualTable.GetVirtualRoute().ShardingKeyToTail(now);
try // try
{ // {
_virtualTableManager.AddPhysicTable(virtualTable, new DefaultPhysicTable(virtualTable, tail)); // _virtualTableManager.AddPhysicTable(virtualTable, new DefaultPhysicTable(virtualTable, tail));
_tableCreator.CreateTable<SysUserLogByMonth>(tail); // _tableCreator.CreateTable<SysUserLogByMonth>(tail);
} // }
catch (Exception e) // catch (Exception e)
{ // {
//ignore // //ignore
Console.WriteLine(e); // Console.WriteLine(e);
} // }
} // }
} // }
return Ok(); // return Ok();
} // }
} // }
} // }

View File

@ -31,7 +31,7 @@ namespace Sample.MySql
using (var scope=app.ApplicationServices.CreateScope()) using (var scope=app.ApplicationServices.CreateScope())
{ {
var virtualDbContext =scope.ServiceProvider.GetService<DefaultTableDbContext>(); var virtualDbContext =scope.ServiceProvider.GetService<DefaultTableDbContext>();
if (!virtualDbContext.Set<SysUserMod>().ShardingAny()) if (!virtualDbContext.Set<SysUserMod>().Any())
{ {
var ids = Enumerable.Range(1, 1000); var ids = Enumerable.Range(1, 1000);
var userMods = new List<SysUserMod>(); var userMods = new List<SysUserMod>();

View File

@ -1,6 +1,7 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Sample.MySql.Domain.Maps; using Sample.MySql.Domain.Maps;
using ShardingCore.DbContexts.ShardingDbContexts; using ShardingCore.DbContexts.ShardingDbContexts;
using ShardingCore.Sharding.Abstractions;
namespace Sample.MySql.DbContexts namespace Sample.MySql.DbContexts
{ {

View File

@ -4,15 +4,6 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Sample.MySql.DbContexts;
using Sample.MySql.Shardings;
using ShardingCore.MySql;
namespace Sample.MySql namespace Sample.MySql
{ {
@ -29,24 +20,24 @@ namespace Sample.MySql
public void ConfigureServices(IServiceCollection services) public void ConfigureServices(IServiceCollection services)
{ {
services.AddControllers(); services.AddControllers();
services.AddShardingMySql(o => // services.AddShardingMySql(o =>
{ // {
o.EnsureCreatedWithOutShardingTable = true; // o.EnsureCreatedWithOutShardingTable = true;
o.CreateShardingTableOnStart = true; // o.CreateShardingTableOnStart = true;
o.UseShardingDbContext<DefaultTableDbContext>( dbConfig => // o.UseShardingDbContext<DefaultTableDbContext>( dbConfig =>
{ // {
dbConfig.AddShardingTableRoute<SysUserModVirtualTableRoute>(); // dbConfig.AddShardingTableRoute<SysUserModVirtualTableRoute>();
dbConfig.AddShardingTableRoute<SysUserLogByMonthRoute>(); // dbConfig.AddShardingTableRoute<SysUserLogByMonthRoute>();
}); // });
//o.AddDataSourceVirtualRoute<>(); // //o.AddDataSourceVirtualRoute<>();
o.IgnoreCreateTableError = true; // o.IgnoreCreateTableError = true;
//
}); // });
services.AddDbContext<DefaultTableDbContext>(o => o.UseMySql("server=xxx;userid=xxx;password=xxx;database=sharding_db123;Charset=utf8;Allow Zero Datetime=True; Pooling=true; Max Pool Size=512;sslmode=none;Allow User Variables=True;", o => // services.AddDbContext<DefaultTableDbContext>(o => o.UseMySql("server=xxx;userid=xxx;password=xxx;database=sharding_db123;Charset=utf8;Allow Zero Datetime=True; Pooling=true; Max Pool Size=512;sslmode=none;Allow User Variables=True;", o =>
{ // {
o.ServerVersion("5.7.13"); // o.ServerVersion("5.7.13");
}).UseShardingMySqlUpdateSqlGenerator()); // }).UseShardingMySqlUpdateSqlGenerator());
services.AddLogging(b => b.AddConsole()); // services.AddLogging(b => b.AddConsole());
} }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

View File

@ -1,6 +1,7 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Sample.SqlServer3x.Domain.Maps; using Sample.SqlServer3x.Domain.Maps;
using ShardingCore.DbContexts.ShardingDbContexts; using ShardingCore.DbContexts.ShardingDbContexts;
using ShardingCore.Sharding.Abstractions;
namespace Sample.SqlServer3x namespace Sample.SqlServer3x
{ {

View File

@ -11,11 +11,7 @@ using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Sample.SqlServer3x.Domain.Entities; using Sample.SqlServer3x.Domain.Entities;
using Sample.SqlServer3x.Shardings;
using ShardingCore; using ShardingCore;
using ShardingCore.DbContexts.VirtualDbContexts;
using ShardingCore.Extensions;
using ShardingCore.SqlServer;
namespace Sample.SqlServer3x namespace Sample.SqlServer3x
{ {
@ -32,19 +28,19 @@ namespace Sample.SqlServer3x
public void ConfigureServices(IServiceCollection services) public void ConfigureServices(IServiceCollection services)
{ {
services.AddControllers(); services.AddControllers();
services.AddShardingSqlServer(o => // services.AddShardingSqlServer(o =>
{ // {
o.EnsureCreatedWithOutShardingTable = true; // o.EnsureCreatedWithOutShardingTable = true;
o.CreateShardingTableOnStart = true; // o.CreateShardingTableOnStart = true;
o.UseShardingDbContext<DefaultDbContext>( dbConfig => // o.UseShardingDbContext<DefaultDbContext>( dbConfig =>
{ // {
dbConfig.AddShardingTableRoute<SysUserModVirtualTableRoute>(); // dbConfig.AddShardingTableRoute<SysUserModVirtualTableRoute>();
}); // });
//o.AddDataSourceVirtualRoute<>(); // //o.AddDataSourceVirtualRoute<>();
//
}); // });
services.AddDbContext<DefaultDbContext>(o => o.UseSqlServer("Data Source=localhost;Initial Catalog=ShardingCoreDB3x;Integrated Security=True") // services.AddDbContext<DefaultDbContext>(o => o.UseSqlServer("Data Source=localhost;Initial Catalog=ShardingCoreDB3x;Integrated Security=True")
.UseShardingSqlServerUpdateSqlGenerator()); // .UseShardingSqlServerUpdateSqlGenerator());
} }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
@ -80,7 +76,7 @@ namespace Sample.SqlServer3x
using (var scope = serviceProvider.CreateScope()) using (var scope = serviceProvider.CreateScope())
{ {
var virtualDbContext = scope.ServiceProvider.GetService<DefaultDbContext>(); var virtualDbContext = scope.ServiceProvider.GetService<DefaultDbContext>();
if (!await virtualDbContext.Set<SysUserMod>().ShardingAnyAsync(o => true)) if (!await virtualDbContext.Set<SysUserMod>().AnyAsync(o => true))
{ {
var ids = Enumerable.Range(1, 1000); var ids = Enumerable.Range(1, 1000);
var userMods = new List<SysUserMod>(); var userMods = new List<SysUserMod>();

View File

@ -12,8 +12,6 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models;
using Samples.AutoByDate.SqlServer.Shardings;
using ShardingCore.SqlServer;
namespace Samples.AutoByDate.SqlServer namespace Samples.AutoByDate.SqlServer
{ {

View File

@ -1,5 +1,6 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using ShardingCore.DbContexts.ShardingDbContexts; using ShardingCore.DbContexts.ShardingDbContexts;
using ShardingCore.Sharding.Abstractions;
using ShardingCore.Test50.MySql.Domain.Maps; using ShardingCore.Test50.MySql.Domain.Maps;
namespace ShardingCore.Test50.MySql namespace ShardingCore.Test50.MySql

View File

@ -1,353 +1,353 @@
using System.Linq; // using System.Linq;
using System.Threading.Tasks; // using System.Threading.Tasks;
using ShardingCore.Core.VirtualRoutes.TableRoutes.RoutingRuleEngine; // using ShardingCore.Core.VirtualRoutes.TableRoutes.RoutingRuleEngine;
using ShardingCore.DbContexts.VirtualDbContexts; // using ShardingCore.DbContexts.VirtualDbContexts;
using ShardingCore.Extensions; // using ShardingCore.Extensions;
using ShardingCore.Test50.MySql.Domain.Entities; // using ShardingCore.Test50.MySql.Domain.Entities;
using Xunit; // using Xunit;
//
namespace ShardingCore.Test50.MySql // namespace ShardingCore.Test50.MySql
{ // {
/* // /*
* @Author: xjm // * @Author: xjm
* @Description: // * @Description:
* @Date: Friday, 15 January 2021 17:22:10 // * @Date: Friday, 15 January 2021 17:22:10
* @Email: 326308290@qq.com // * @Email: 326308290@qq.com
*/ // */
public class ShardingTest // public class ShardingTest
{ // {
private readonly DefaultDbContext _virtualDbContext; // private readonly DefaultDbContext _virtualDbContext;
private readonly IRoutingRuleEngineFactory _routingRuleEngineFactory; // private readonly IRoutingRuleEngineFactory _routingRuleEngineFactory;
//
public ShardingTest(DefaultDbContext virtualDbContext,IRoutingRuleEngineFactory routingRuleEngineFactory) // public ShardingTest(DefaultDbContext virtualDbContext,IRoutingRuleEngineFactory routingRuleEngineFactory)
{ // {
_virtualDbContext = virtualDbContext; // _virtualDbContext = virtualDbContext;
_routingRuleEngineFactory = routingRuleEngineFactory; // _routingRuleEngineFactory = routingRuleEngineFactory;
} // }
//
//[Fact] // //[Fact]
//public async Task Route_TEST() // //public async Task Route_TEST()
//{ // //{
// var queryable1 = _virtualDbContext.Set<SysUserMod>().Where(o=>o.Id=="339"); // // var queryable1 = _virtualDbContext.Set<SysUserMod>().Where(o=>o.Id=="339");
// var routeResults1 = _routingRuleEngineFactory.Route(queryable1); // // var routeResults1 = _routingRuleEngineFactory.Route(queryable1);
// Assert.Equal(1,routeResults1.Count()); // // Assert.Equal(1,routeResults1.Count());
// Assert.Equal(1,routeResults1.FirstOrDefault().ReplaceTables.Count()); // // Assert.Equal(1,routeResults1.FirstOrDefault().ReplaceTables.Count());
// Assert.Equal("0",routeResults1.FirstOrDefault().ReplaceTables.FirstOrDefault().Tail); // // Assert.Equal("0",routeResults1.FirstOrDefault().ReplaceTables.FirstOrDefault().Tail);
// Assert.Equal(nameof(SysUserMod),routeResults1.FirstOrDefault().ReplaceTables.FirstOrDefault().OriginalName); // // Assert.Equal(nameof(SysUserMod),routeResults1.FirstOrDefault().ReplaceTables.FirstOrDefault().OriginalName);
// var ids = new[] {"339", "124","142"}; // // var ids = new[] {"339", "124","142"};
// var queryable2= _virtualDbContext.Set<SysUserMod>().Where(o=>ids.Contains(o.Id)); // // var queryable2= _virtualDbContext.Set<SysUserMod>().Where(o=>ids.Contains(o.Id));
// var routeResult2s = _routingRuleEngineFactory.Route(queryable2); // // var routeResult2s = _routingRuleEngineFactory.Route(queryable2);
// Assert.Equal(2,routeResult2s.Count()); // // Assert.Equal(2,routeResult2s.Count());
// Assert.Equal(1,routeResult2s.FirstOrDefault().ReplaceTables.Count()); // // Assert.Equal(1,routeResult2s.FirstOrDefault().ReplaceTables.Count());
// Assert.Equal(2,routeResult2s.SelectMany(o=>o.ReplaceTables).Count()); // // Assert.Equal(2,routeResult2s.SelectMany(o=>o.ReplaceTables).Count());
// Assert.Equal(true,routeResult2s.SelectMany(o=>o.ReplaceTables).All(o=>new[]{"0","1"}.Contains(o.Tail))); // // Assert.Equal(true,routeResult2s.SelectMany(o=>o.ReplaceTables).All(o=>new[]{"0","1"}.Contains(o.Tail)));
//} // //}
//
[Fact] // [Fact]
public async Task ToList_All_Test() // public async Task ToList_All_Test()
{ // {
var mods = await _virtualDbContext.Set<SysUserMod>().ToShardingListAsync(); // var mods = await _virtualDbContext.Set<SysUserMod>().ToShardingListAsync();
Assert.Equal(1000, mods.Count); // Assert.Equal(1000, mods.Count);
} // }
//
[Fact] // [Fact]
public async Task ToList_Join_Test() // public async Task ToList_Join_Test()
{ // {
var list = await (from u in _virtualDbContext.Set<SysUserMod>() // var list = await (from u in _virtualDbContext.Set<SysUserMod>()
join salary in _virtualDbContext.Set<SysUserSalary>() // join salary in _virtualDbContext.Set<SysUserSalary>()
on u.Id equals salary.UserId // on u.Id equals salary.UserId
select new // select new
{ // {
Salary = salary.Salary, // Salary = salary.Salary,
DateOfMonth = salary.DateOfMonth, // DateOfMonth = salary.DateOfMonth,
Name = u.Name // Name = u.Name
}).ToShardingListAsync(); // }).ToShardingListAsync();
Assert.Equal(24000, list.Count()); // Assert.Equal(24000, list.Count());
Assert.Equal(24, list.Count(o => o.Name == "name_200")); // Assert.Equal(24, list.Count(o => o.Name == "name_200"));
//
//
var queryable = (from u in _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "300") // var queryable = (from u in _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "300")
join salary in _virtualDbContext.Set<SysUserSalary>() // join salary in _virtualDbContext.Set<SysUserSalary>()
on u.Id equals salary.UserId // on u.Id equals salary.UserId
select new // select new
{ // {
Salary = salary.Salary, // Salary = salary.Salary,
DateOfMonth = salary.DateOfMonth, // DateOfMonth = salary.DateOfMonth,
Name = u.Name // Name = u.Name
}); // });
var list1 = await queryable.ToShardingListAsync(); // var list1 = await queryable.ToShardingListAsync();
Assert.Equal(24, list1.Count()); // Assert.Equal(24, list1.Count());
Assert.DoesNotContain(list1, o => o.Name != "name_300"); // Assert.DoesNotContain(list1, o => o.Name != "name_300");
} // }
//
[Fact] // [Fact]
public async Task ToList_OrderBy_Asc_Desc_Test() // public async Task ToList_OrderBy_Asc_Desc_Test()
{ // {
var modascs = await _virtualDbContext.Set<SysUserMod>().OrderBy(o => o.Age).ToShardingListAsync(); // var modascs = await _virtualDbContext.Set<SysUserMod>().OrderBy(o => o.Age).ToShardingListAsync();
Assert.Equal(1000, modascs.Count); // Assert.Equal(1000, modascs.Count);
var i = 1; // var i = 1;
foreach (var age in modascs) // foreach (var age in modascs)
{ // {
Assert.Equal(i, age.Age); // Assert.Equal(i, age.Age);
i++; // i++;
} // }
//
var moddescs = await _virtualDbContext.Set<SysUserMod>().OrderByDescending(o => o.Age).ToShardingListAsync(); // var moddescs = await _virtualDbContext.Set<SysUserMod>().OrderByDescending(o => o.Age).ToShardingListAsync();
Assert.Equal(1000, moddescs.Count); // Assert.Equal(1000, moddescs.Count);
var j = 1000; // var j = 1000;
foreach (var age in moddescs) // foreach (var age in moddescs)
{ // {
Assert.Equal(j, age.Age); // Assert.Equal(j, age.Age);
j--; // j--;
} // }
} // }
//
[Fact] // [Fact]
public async Task ToList_Id_In_Test() // public async Task ToList_Id_In_Test()
{ // {
var ids = new[] {"1", "2", "3", "4"}; // var ids = new[] {"1", "2", "3", "4"};
var sysUserMods = await _virtualDbContext.Set<SysUserMod>().Where(o => ids.Contains(o.Id)).ToShardingListAsync(); // var sysUserMods = await _virtualDbContext.Set<SysUserMod>().Where(o => ids.Contains(o.Id)).ToShardingListAsync();
foreach (var id in ids) // foreach (var id in ids)
{ // {
Assert.Contains(sysUserMods, o => o.Id == id); // Assert.Contains(sysUserMods, o => o.Id == id);
} // }
//
Assert.DoesNotContain(sysUserMods, o => o.Age > 4); // Assert.DoesNotContain(sysUserMods, o => o.Age > 4);
} // }
//
[Fact] // [Fact]
public async Task ToList_Id_Eq_Test() // public async Task ToList_Id_Eq_Test()
{ // {
var mods = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "3").ToShardingListAsync(); // var mods = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "3").ToShardingListAsync();
Assert.Single(mods); // Assert.Single(mods);
Assert.Equal("3", mods[0].Id); // Assert.Equal("3", mods[0].Id);
} // }
//
[Fact] // [Fact]
public async Task ToList_Id_Not_Eq_Test() // public async Task ToList_Id_Not_Eq_Test()
{ // {
var mods = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id != "3").ToShardingListAsync(); // var mods = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id != "3").ToShardingListAsync();
Assert.Equal(999, mods.Count); // Assert.Equal(999, mods.Count);
Assert.DoesNotContain(mods, o => o.Id == "3"); // Assert.DoesNotContain(mods, o => o.Id == "3");
} // }
//
[Fact] // [Fact]
public async Task ToList_Id_Not_Eq_Skip_Test() // public async Task ToList_Id_Not_Eq_Skip_Test()
{ // {
var mods = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id != "3").OrderBy(o => o.Age).Skip(2).ToShardingListAsync(); // var mods = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id != "3").OrderBy(o => o.Age).Skip(2).ToShardingListAsync();
Assert.Equal(997, mods.Count); // Assert.Equal(997, mods.Count);
Assert.DoesNotContain(mods, o => o.Id == "3"); // Assert.DoesNotContain(mods, o => o.Id == "3");
Assert.Equal(4, mods[0].Age); // Assert.Equal(4, mods[0].Age);
Assert.Equal(5, mods[1].Age); // Assert.Equal(5, mods[1].Age);
//
var modsDesc = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id != "3").OrderByDescending(o => o.Age).Skip(13).ToShardingListAsync(); // var modsDesc = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id != "3").OrderByDescending(o => o.Age).Skip(13).ToShardingListAsync();
Assert.Equal(986, modsDesc.Count); // Assert.Equal(986, modsDesc.Count);
Assert.DoesNotContain(mods, o => o.Id == "3"); // Assert.DoesNotContain(mods, o => o.Id == "3");
Assert.Equal(987, modsDesc[0].Age); // Assert.Equal(987, modsDesc[0].Age);
Assert.Equal(986, modsDesc[1].Age); // Assert.Equal(986, modsDesc[1].Age);
} // }
//
[Fact] // [Fact]
public async Task ToList_Name_Eq_Test() // public async Task ToList_Name_Eq_Test()
{ // {
var mods = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name == "name_3").ToShardingListAsync(); // var mods = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name == "name_3").ToShardingListAsync();
Assert.Single(mods); // Assert.Single(mods);
Assert.Equal("3", mods[0].Id); // Assert.Equal("3", mods[0].Id);
} // }
//
[Fact] // [Fact]
public async Task ToList_Id_Eq_Not_In_Db_Test() // public async Task ToList_Id_Eq_Not_In_Db_Test()
{ // {
var mods = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "1001").ToShardingListAsync(); // var mods = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "1001").ToShardingListAsync();
Assert.Empty(mods); // Assert.Empty(mods);
} // }
//
[Fact] // [Fact]
public async Task ToList_Name_Eq_Not_In_Db_Test() // public async Task ToList_Name_Eq_Not_In_Db_Test()
{ // {
var mods = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name == "name_1001").ToShardingListAsync(); // var mods = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name == "name_1001").ToShardingListAsync();
Assert.Empty(mods); // Assert.Empty(mods);
} // }
//
[Fact] // [Fact]
public async Task FirstOrDefault_Order_By_Id_Test() // public async Task FirstOrDefault_Order_By_Id_Test()
{ // {
var sysUserModAge = await _virtualDbContext.Set<SysUserMod>().OrderBy(o => o.Age).ShardingFirstOrDefaultAsync(); // var sysUserModAge = await _virtualDbContext.Set<SysUserMod>().OrderBy(o => o.Age).ShardingFirstOrDefaultAsync();
Assert.True(sysUserModAge != null && sysUserModAge.Id == "1"); // Assert.True(sysUserModAge != null && sysUserModAge.Id == "1");
var sysUserModAgeDesc = await _virtualDbContext.Set<SysUserMod>().OrderByDescending(o => o.Age).ShardingFirstOrDefaultAsync(); // var sysUserModAgeDesc = await _virtualDbContext.Set<SysUserMod>().OrderByDescending(o => o.Age).ShardingFirstOrDefaultAsync();
Assert.True(sysUserModAgeDesc != null && sysUserModAgeDesc.Id == "1000"); // Assert.True(sysUserModAgeDesc != null && sysUserModAgeDesc.Id == "1000");
var sysUserMod = await _virtualDbContext.Set<SysUserMod>().OrderBy(o => o.Id).ShardingFirstOrDefaultAsync(); // var sysUserMod = await _virtualDbContext.Set<SysUserMod>().OrderBy(o => o.Id).ShardingFirstOrDefaultAsync();
Assert.True(sysUserMod != null && sysUserMod.Id == "1"); // Assert.True(sysUserMod != null && sysUserMod.Id == "1");
//
var sysUserModDesc = await _virtualDbContext.Set<SysUserMod>().OrderByDescending(o => o.Id).ShardingFirstOrDefaultAsync(); // var sysUserModDesc = await _virtualDbContext.Set<SysUserMod>().OrderByDescending(o => o.Id).ShardingFirstOrDefaultAsync();
Assert.True(sysUserModDesc != null && sysUserModDesc.Id == "999"); // Assert.True(sysUserModDesc != null && sysUserModDesc.Id == "999");
} // }
//
[Fact] // [Fact]
public async Task FirstOrDefault2() // public async Task FirstOrDefault2()
{ // {
var sysUserMod = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "1").ShardingFirstOrDefaultAsync(); // var sysUserMod = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "1").ShardingFirstOrDefaultAsync();
Assert.NotNull(sysUserMod); // Assert.NotNull(sysUserMod);
Assert.True(sysUserMod.Id == "1"); // Assert.True(sysUserMod.Id == "1");
} // }
//
[Fact] // [Fact]
public async Task FirstOrDefault3() // public async Task FirstOrDefault3()
{ // {
var sysUserMod = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name == "name_2").ShardingFirstOrDefaultAsync(); // var sysUserMod = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name == "name_2").ShardingFirstOrDefaultAsync();
Assert.NotNull(sysUserMod); // Assert.NotNull(sysUserMod);
Assert.Equal("2", sysUserMod.Id); // Assert.Equal("2", sysUserMod.Id);
} // }
//
[Fact] // [Fact]
public async Task FirstOrDefault4() // public async Task FirstOrDefault4()
{ // {
var sysUserMod = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id != "1").ShardingFirstOrDefaultAsync(); // var sysUserMod = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id != "1").ShardingFirstOrDefaultAsync();
Assert.NotNull(sysUserMod); // Assert.NotNull(sysUserMod);
Assert.True(sysUserMod.Id != "1"); // Assert.True(sysUserMod.Id != "1");
} // }
//
[Fact] // [Fact]
public async Task FirstOrDefault5() // public async Task FirstOrDefault5()
{ // {
var sysUserMod = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name == "name_1001").ShardingFirstOrDefaultAsync(); // var sysUserMod = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name == "name_1001").ShardingFirstOrDefaultAsync();
Assert.Null(sysUserMod); // Assert.Null(sysUserMod);
} // }
//
[Fact] // [Fact]
public async Task Count_Test() // public async Task Count_Test()
{ // {
var a = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name == "name_1000").ShardingCountAsync(); // var a = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name == "name_1000").ShardingCountAsync();
Assert.Equal(1, a); // Assert.Equal(1, a);
var b = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name != "name_1000").ShardingCountAsync(); // var b = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name != "name_1000").ShardingCountAsync();
Assert.Equal(999, b); // Assert.Equal(999, b);
} // }
//
[Fact] // [Fact]
public async Task Sum_Test() // public async Task Sum_Test()
{ // {
var a = await _virtualDbContext.Set<SysUserMod>().ShardingSumAsync(o => o.Age); // var a = await _virtualDbContext.Set<SysUserMod>().ShardingSumAsync(o => o.Age);
var expected = 0; // var expected = 0;
for (int i = 1; i <= 1000; i++) // for (int i = 1; i <= 1000; i++)
{ // {
expected += i; // expected += i;
} // }
//
Assert.Equal(expected, a); // Assert.Equal(expected, a);
var b = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name != "name_1000").ShardingSumAsync(o => o.Age); // var b = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name != "name_1000").ShardingSumAsync(o => o.Age);
Assert.Equal(expected - 1000, b); // Assert.Equal(expected - 1000, b);
} // }
//
[Fact] // [Fact]
public async Task Max_Test() // public async Task Max_Test()
{ // {
var a = await _virtualDbContext.Set<SysUserMod>().ShardingMaxAsync(o => o.Age); // var a = await _virtualDbContext.Set<SysUserMod>().ShardingMaxAsync(o => o.Age);
Assert.Equal(1000, a); // Assert.Equal(1000, a);
var b = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name != "name_1000").ShardingMaxAsync(o => o.Age); // var b = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name != "name_1000").ShardingMaxAsync(o => o.Age);
Assert.Equal(999, b); // Assert.Equal(999, b);
var c = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Age < 500).ShardingMaxAsync(o => o.Age); // var c = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Age < 500).ShardingMaxAsync(o => o.Age);
Assert.Equal(499, c); // Assert.Equal(499, c);
var e = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Age <= 500).ShardingMaxAsync(o => o.Age); // var e = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Age <= 500).ShardingMaxAsync(o => o.Age);
Assert.Equal(500, e); // Assert.Equal(500, e);
} // }
//
[Fact] // [Fact]
public async Task Max_Join_Test() // public async Task Max_Join_Test()
{ // {
var queryable = (from u in _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "300") // var queryable = (from u in _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "300")
join salary in _virtualDbContext.Set<SysUserSalary>() // join salary in _virtualDbContext.Set<SysUserSalary>()
on u.Id equals salary.UserId // on u.Id equals salary.UserId
select new // select new
{ // {
Salary = salary.Salary, // Salary = salary.Salary,
DateOfMonth = salary.DateOfMonth, // DateOfMonth = salary.DateOfMonth,
Name = u.Name // Name = u.Name
}); // });
var maxSalary = await queryable.ShardingMaxAsync(o => o.Salary); // var maxSalary = await queryable.ShardingMaxAsync(o => o.Salary);
Assert.Equal(1390000, maxSalary); // Assert.Equal(1390000, maxSalary);
} // }
//
[Fact] // [Fact]
public async Task Min_Test() // public async Task Min_Test()
{ // {
var a = await _virtualDbContext.Set<SysUserMod>().ShardingMinAsync(o => o.Age); // var a = await _virtualDbContext.Set<SysUserMod>().ShardingMinAsync(o => o.Age);
Assert.Equal(1, a); // Assert.Equal(1, a);
var b = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name != "name_1").ShardingMinAsync(o => o.Age); // var b = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name != "name_1").ShardingMinAsync(o => o.Age);
Assert.Equal(2, b); // Assert.Equal(2, b);
var c = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Age > 500).ShardingMinAsync(o => o.Age); // var c = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Age > 500).ShardingMinAsync(o => o.Age);
Assert.Equal(501, c); // Assert.Equal(501, c);
var e = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Age >= 500).ShardingMinAsync(o => o.Age); // var e = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Age >= 500).ShardingMinAsync(o => o.Age);
Assert.Equal(500, e); // Assert.Equal(500, e);
} // }
//
[Fact] // [Fact]
public async Task Any_Test() // public async Task Any_Test()
{ // {
var a = await _virtualDbContext.Set<SysUserMod>().ShardingAnyAsync(o => o.Age == 100); // var a = await _virtualDbContext.Set<SysUserMod>().ShardingAnyAsync(o => o.Age == 100);
Assert.True(a); // Assert.True(a);
var b = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name != "name_1").ShardingAnyAsync(o => o.Age == 1); // var b = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name != "name_1").ShardingAnyAsync(o => o.Age == 1);
Assert.False(b); // Assert.False(b);
var c = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Age > 500).ShardingAnyAsync(o => o.Age <= 500); // var c = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Age > 500).ShardingAnyAsync(o => o.Age <= 500);
Assert.False(c); // Assert.False(c);
var e = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Age >= 500).ShardingAnyAsync(o => o.Age <= 500); // var e = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Age >= 500).ShardingAnyAsync(o => o.Age <= 500);
Assert.True(e); // Assert.True(e);
} // }
//
[Fact] // [Fact]
public async Task Group_Test() // public async Task Group_Test()
{ // {
var ids = new[] {"200", "300"}; // var ids = new[] {"200", "300"};
var dateOfMonths = new[] {202111, 202110}; // var dateOfMonths = new[] {202111, 202110};
var group = await (from u in _virtualDbContext.Set<SysUserSalary>() // var group = await (from u in _virtualDbContext.Set<SysUserSalary>()
.Where(o => ids.Contains(o.UserId) && dateOfMonths.Contains(o.DateOfMonth)) // .Where(o => ids.Contains(o.UserId) && dateOfMonths.Contains(o.DateOfMonth))
group u by new // group u by new
{ // {
UId = u.UserId // UId = u.UserId
} // }
into g // into g
select new // select new
{ // {
GroupUserId = g.Key.UId, // GroupUserId = g.Key.UId,
Count = g.Count(), // Count = g.Count(),
TotalSalary = g.Sum(o => o.Salary), // TotalSalary = g.Sum(o => o.Salary),
AvgSalary = g.Average(o => o.Salary), // AvgSalary = g.Average(o => o.Salary),
AvgSalaryDecimal = g.Average(o => o.SalaryDecimal), // AvgSalaryDecimal = g.Average(o => o.SalaryDecimal),
MinSalary = g.Min(o => o.Salary), // MinSalary = g.Min(o => o.Salary),
MaxSalary = g.Max(o => o.Salary) // MaxSalary = g.Max(o => o.Salary)
}).ToShardingListAsync(); // }).ToShardingListAsync();
Assert.Equal(2, group.Count); // Assert.Equal(2, group.Count);
Assert.Equal(2, group[0].Count); // Assert.Equal(2, group[0].Count);
Assert.Equal(2260000, group[0].TotalSalary); // Assert.Equal(2260000, group[0].TotalSalary);
Assert.Equal(1130000, group[0].AvgSalary); // Assert.Equal(1130000, group[0].AvgSalary);
Assert.Equal(11300, group[0].AvgSalaryDecimal); // Assert.Equal(11300, group[0].AvgSalaryDecimal);
Assert.Equal(1120000, group[0].MinSalary); // Assert.Equal(1120000, group[0].MinSalary);
Assert.Equal(1140000, group[0].MaxSalary); // Assert.Equal(1140000, group[0].MaxSalary);
} // }
[Fact] // [Fact]
public async Task Group_API_Test() // public async Task Group_API_Test()
{ // {
var ids = new[] {"200", "300"}; // var ids = new[] {"200", "300"};
var dateOfMonths = new[] {202111, 202110}; // var dateOfMonths = new[] {202111, 202110};
var group = await _virtualDbContext.Set<SysUserSalary>() // var group = await _virtualDbContext.Set<SysUserSalary>()
.Where(o => ids.Contains(o.UserId) && dateOfMonths.Contains(o.DateOfMonth)) // .Where(o => ids.Contains(o.UserId) && dateOfMonths.Contains(o.DateOfMonth))
.ShardingGroupByAsync(g => new {UId = g.UserId}, g => new // .ShardingGroupByAsync(g => new {UId = g.UserId}, g => new
{ // {
//
GroupUserId = g.Key.UId, // GroupUserId = g.Key.UId,
Count = g.Count(), // Count = g.Count(),
TotalSalary = g.Sum(o => o.Salary), // TotalSalary = g.Sum(o => o.Salary),
AvgSalary = g.Average(o => o.Salary), // AvgSalary = g.Average(o => o.Salary),
AvgSalaryDecimal = g.Average(o => o.SalaryDecimal), // AvgSalaryDecimal = g.Average(o => o.SalaryDecimal),
MinSalary = g.Min(o => o.Salary), // MinSalary = g.Min(o => o.Salary),
MaxSalary = g.Max(o => o.Salary) // MaxSalary = g.Max(o => o.Salary)
}); // });
Assert.Equal(2, group.Count); // Assert.Equal(2, group.Count);
Assert.Equal(2, group[0].Count); // Assert.Equal(2, group[0].Count);
Assert.Equal(2260000, group[0].TotalSalary); // Assert.Equal(2260000, group[0].TotalSalary);
Assert.Equal(1130000, group[0].AvgSalary); // Assert.Equal(1130000, group[0].AvgSalary);
Assert.Equal(11300, group[0].AvgSalaryDecimal); // Assert.Equal(11300, group[0].AvgSalaryDecimal);
Assert.Equal(1120000, group[0].MinSalary); // Assert.Equal(1120000, group[0].MinSalary);
Assert.Equal(1140000, group[0].MaxSalary); // Assert.Equal(1140000, group[0].MaxSalary);
} // }
} // }
} // }

View File

@ -10,8 +10,6 @@ using ShardingCore.DbContexts.VirtualDbContexts;
using ShardingCore.Extensions; using ShardingCore.Extensions;
using ShardingCore.Test50.MySql.Domain.Entities; using ShardingCore.Test50.MySql.Domain.Entities;
using ShardingCore.MySql;
using ShardingCore.Test50.MySql.Shardings;
namespace ShardingCore.Test50.MySql namespace ShardingCore.Test50.MySql
{ {
@ -40,23 +38,23 @@ namespace ShardingCore.Test50.MySql
public void ConfigureServices(IServiceCollection services, HostBuilderContext hostBuilderContext) public void ConfigureServices(IServiceCollection services, HostBuilderContext hostBuilderContext)
{ {
services.AddShardingMySql(o => // services.AddShardingMySql(o =>
{ // {
o.EnsureCreatedWithOutShardingTable = false; // o.EnsureCreatedWithOutShardingTable = false;
o.CreateShardingTableOnStart = false; // o.CreateShardingTableOnStart = false;
// o.AddShardingTable<DefaultDbContext>("conn1", "server=xxx;userid=xxx;password=xxx;database=sharding_db123;Charset=utf8;Allow Zero Datetime=True; Pooling=true; Max Pool Size=512;sslmode=none;Allow User Variables=True;", dbConfig => // // o.AddShardingTable<DefaultDbContext>("conn1", "server=xxx;userid=xxx;password=xxx;database=sharding_db123;Charset=utf8;Allow Zero Datetime=True; Pooling=true; Max Pool Size=512;sslmode=none;Allow User Variables=True;", dbConfig =>
o.UseShardingDbContext<DefaultDbContext>( dbConfig => // o.UseShardingDbContext<DefaultDbContext>( dbConfig =>
{ // {
dbConfig.AddShardingTableRoute<SysUserModVirtualTableRoute>(); // dbConfig.AddShardingTableRoute<SysUserModVirtualTableRoute>();
dbConfig.AddShardingTableRoute<SysUserSalaryVirtualTableRoute>(); // dbConfig.AddShardingTableRoute<SysUserSalaryVirtualTableRoute>();
}); // });
//o.AddDataSourceVirtualRoute<>(); // //o.AddDataSourceVirtualRoute<>();
o.IgnoreCreateTableError = true; // o.IgnoreCreateTableError = true;
o.ServerVersion = new MySqlServerVersion("5.7.15"); // o.ServerVersion = new MySqlServerVersion("5.7.15");
}); // });
services.AddDbContext<DefaultDbContext>(o=> // services.AddDbContext<DefaultDbContext>(o=>
o.UseMySql(hostBuilderContext.Configuration.GetSection("MySql")["ConnectionString"],new MySqlServerVersion("5.7.15")) // o.UseMySql(hostBuilderContext.Configuration.GetSection("MySql")["ConnectionString"],new MySqlServerVersion("5.7.15"))
.UseShardingMySqlUpdateSqlGenerator()); // .UseShardingMySqlUpdateSqlGenerator());
} }
// 可以添加要用到的方法参数,会自动从注册的服务中获取服务实例,类似于 asp.net core 里 Configure 方法 // 可以添加要用到的方法参数,会自动从注册的服务中获取服务实例,类似于 asp.net core 里 Configure 方法
@ -79,7 +77,7 @@ namespace ShardingCore.Test50.MySql
{ {
var virtualDbContext = scope.ServiceProvider.GetService<DefaultDbContext>(); var virtualDbContext = scope.ServiceProvider.GetService<DefaultDbContext>();
if (!await virtualDbContext.Set<SysUserMod>().ShardingAnyAsync(o => true)) if (!await virtualDbContext.Set<SysUserMod>().AnyAsync(o => true))
{ {
var ids = Enumerable.Range(1, 1000); var ids = Enumerable.Range(1, 1000);
var userMods = new List<SysUserMod>(); var userMods = new List<SysUserMod>();

View File

@ -48,17 +48,14 @@ namespace ShardingCore.Test50
public void ConfigureServices(IServiceCollection services, HostBuilderContext hostBuilderContext) public void ConfigureServices(IServiceCollection services, HostBuilderContext hostBuilderContext)
{ {
services.AddDbContext<DefaultDbContext>(o =>
o.UseSqlServer(hostBuilderContext.Configuration.GetSection("SqlServer")["ConnectionString"])); services.AddShardingDbContext<ShardingDefaultDbContext, DefaultDbContext>(o => o.UseSqlServer("Data Source=localhost;Initial Catalog=ShardingCoreDBxx2;Integrated Security=True;MultipleActiveResultSets=True;")
services.AddShardingDbContext<ShardingDefaultDbContext, DefaultDbContext>(o => ,op =>
o.UseSqlServer(hostBuilderContext.Configuration.GetSection("SqlServer")["ConnectionString"]), op =>
{ {
op.EnsureCreatedWithOutShardingTable = true; op.EnsureCreatedWithOutShardingTable = true;
op.CreateShardingTableOnStart = true; op.CreateShardingTableOnStart = true;
op.UseShardingDbContextOptions((connection, builder) => builder.UseSqlServer(connection).UseLoggerFactory(efLogger)); op.UseShardingDbContextOptions((connection, builder) => builder.UseSqlServer(connection).UseLoggerFactory(efLogger));
op.AddShardingTableRoute<SysUserModVirtualTableRoute>(); op.AddShardingTableRoute<SysUserModVirtualTableRoute>();
op.AddShardingTableRoute<SysUserSalaryVirtualTableRoute>();
}); });
} }
@ -68,7 +65,7 @@ namespace ShardingCore.Test50
var shardingBootstrapper = serviceProvider.GetService<IShardingBootstrapper>(); var shardingBootstrapper = serviceProvider.GetService<IShardingBootstrapper>();
shardingBootstrapper.Start(); shardingBootstrapper.Start();
// 有一些测试数据要初始化可以放在这里 // 有一些测试数据要初始化可以放在这里
//InitData(serviceProvider).GetAwaiter().GetResult(); InitData(serviceProvider).GetAwaiter().GetResult();
} }
/// <summary> /// <summary>

View File

@ -1,5 +1,6 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using ShardingCore.DbContexts.ShardingDbContexts; using ShardingCore.DbContexts.ShardingDbContexts;
using ShardingCore.Sharding.Abstractions;
using ShardingCoreTestBatch.Domain.Maps; using ShardingCoreTestBatch.Domain.Maps;
namespace ShardingCoreTestBatch namespace ShardingCoreTestBatch

View File

@ -5,6 +5,7 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using ShardingCore.DbContexts.ShardingDbContexts; using ShardingCore.DbContexts.ShardingDbContexts;
using ShardingCore.Sharding.Abstractions;
using ShardingCoreTestSqlServer3x.Domain.Maps; using ShardingCoreTestSqlServer3x.Domain.Maps;
namespace ShardingCoreTestSqlServer3x namespace ShardingCoreTestSqlServer3x

View File

@ -1,391 +1,391 @@
using System; // using System;
using System.Linq; // using System.Linq;
using System.Threading.Tasks; // using System.Threading.Tasks;
using ShardingCore.Core.VirtualRoutes.TableRoutes.RoutingRuleEngine; // using ShardingCore.Core.VirtualRoutes.TableRoutes.RoutingRuleEngine;
using ShardingCore.DbContexts.VirtualDbContexts; // using ShardingCore.DbContexts.VirtualDbContexts;
using ShardingCore.Extensions; // using ShardingCore.Extensions;
using ShardingCoreTestSqlServer3x.Domain.Entities; // using ShardingCoreTestSqlServer3x.Domain.Entities;
using Xunit; // using Xunit;
//
namespace ShardingCoreTestSqlServer3x // namespace ShardingCoreTestSqlServer3x
{ // {
/* // /*
* @Author: xjm // * @Author: xjm
* @Description: // * @Description:
* @Date: Friday, 15 January 2021 17:22:10 // * @Date: Friday, 15 January 2021 17:22:10
* @Email: 326308290@qq.com // * @Email: 326308290@qq.com
*/ // */
public class ShardingTest // public class ShardingTest
{ // {
private readonly DefaultDbContext _virtualDbContext; // private readonly DefaultDbContext _virtualDbContext;
private readonly IRoutingRuleEngineFactory _routingRuleEngineFactory; // private readonly IRoutingRuleEngineFactory _routingRuleEngineFactory;
//
public ShardingTest(DefaultDbContext virtualDbContext,IRoutingRuleEngineFactory routingRuleEngineFactory) // public ShardingTest(DefaultDbContext virtualDbContext,IRoutingRuleEngineFactory routingRuleEngineFactory)
{ // {
_virtualDbContext = virtualDbContext; // _virtualDbContext = virtualDbContext;
_routingRuleEngineFactory = routingRuleEngineFactory; // _routingRuleEngineFactory = routingRuleEngineFactory;
} // }
//
//[Fact] // //[Fact]
//public async Task Route_TEST() // //public async Task Route_TEST()
//{ // //{
// var queryable1 = _virtualDbContext.Set<SysUserMod>().Where(o=>o.Id=="339"); // // var queryable1 = _virtualDbContext.Set<SysUserMod>().Where(o=>o.Id=="339");
// var routeResults1 = _routingRuleEngineFactory.Route(queryable1); // // var routeResults1 = _routingRuleEngineFactory.Route(queryable1);
// Assert.Equal(1,routeResults1.Count()); // // Assert.Equal(1,routeResults1.Count());
// Assert.Equal(1,routeResults1.FirstOrDefault().ReplaceTables.Count()); // // Assert.Equal(1,routeResults1.FirstOrDefault().ReplaceTables.Count());
// Assert.Equal("0",routeResults1.FirstOrDefault().ReplaceTables.FirstOrDefault().Tail); // // Assert.Equal("0",routeResults1.FirstOrDefault().ReplaceTables.FirstOrDefault().Tail);
// Assert.Equal(nameof(SysUserMod),routeResults1.FirstOrDefault().ReplaceTables.FirstOrDefault().OriginalName); // // Assert.Equal(nameof(SysUserMod),routeResults1.FirstOrDefault().ReplaceTables.FirstOrDefault().OriginalName);
// var ids = new[] {"339", "124","142"}; // // var ids = new[] {"339", "124","142"};
// var queryable2= _virtualDbContext.Set<SysUserMod>().Where(o=>ids.Contains(o.Id)); // // var queryable2= _virtualDbContext.Set<SysUserMod>().Where(o=>ids.Contains(o.Id));
// var routeResult2s = _routingRuleEngineFactory.Route(queryable2); // // var routeResult2s = _routingRuleEngineFactory.Route(queryable2);
// Assert.Equal(2,routeResult2s.Count()); // // Assert.Equal(2,routeResult2s.Count());
// Assert.Equal(1,routeResult2s.FirstOrDefault().ReplaceTables.Count()); // // Assert.Equal(1,routeResult2s.FirstOrDefault().ReplaceTables.Count());
// Assert.Equal(2,routeResult2s.SelectMany(o=>o.ReplaceTables).Count()); // // Assert.Equal(2,routeResult2s.SelectMany(o=>o.ReplaceTables).Count());
// Assert.Equal(true,routeResult2s.SelectMany(o=>o.ReplaceTables).All(o=>new[]{"0","1"}.Contains(o.Tail))); // // Assert.Equal(true,routeResult2s.SelectMany(o=>o.ReplaceTables).All(o=>new[]{"0","1"}.Contains(o.Tail)));
//} // //}
[Fact] // [Fact]
public async Task ToList_All_Test() // public async Task ToList_All_Test()
{ // {
var mods = await _virtualDbContext.Set<SysUserMod>().ToShardingListAsync(); // var mods = await _virtualDbContext.Set<SysUserMod>().ToShardingListAsync();
Assert.Equal(1000, mods.Count); // Assert.Equal(1000, mods.Count);
} // }
//
[Fact] // [Fact]
public async Task ToList_Join_Test() // public async Task ToList_Join_Test()
{ // {
var list = await (from u in _virtualDbContext.Set<SysUserMod>() // var list = await (from u in _virtualDbContext.Set<SysUserMod>()
join salary in _virtualDbContext.Set<SysUserSalary>() // join salary in _virtualDbContext.Set<SysUserSalary>()
on u.Id equals salary.UserId // on u.Id equals salary.UserId
select new // select new
{ // {
Salary = salary.Salary, // Salary = salary.Salary,
DateOfMonth = salary.DateOfMonth, // DateOfMonth = salary.DateOfMonth,
Name = u.Name // Name = u.Name
}).ToShardingListAsync(); // }).ToShardingListAsync();
Assert.Equal(24000, list.Count()); // Assert.Equal(24000, list.Count());
Assert.Equal(24, list.Count(o => o.Name == "name_200")); // Assert.Equal(24, list.Count(o => o.Name == "name_200"));
//
//
var queryable = (from u in _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "300") // var queryable = (from u in _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "300")
join salary in _virtualDbContext.Set<SysUserSalary>() // join salary in _virtualDbContext.Set<SysUserSalary>()
on u.Id equals salary.UserId // on u.Id equals salary.UserId
select new // select new
{ // {
Salary = salary.Salary, // Salary = salary.Salary,
DateOfMonth = salary.DateOfMonth, // DateOfMonth = salary.DateOfMonth,
Name = u.Name // Name = u.Name
}); // });
var list1 = await queryable.ToShardingListAsync(); // var list1 = await queryable.ToShardingListAsync();
Assert.Equal(24, list1.Count()); // Assert.Equal(24, list1.Count());
Assert.DoesNotContain(list1, o => o.Name != "name_300"); // Assert.DoesNotContain(list1, o => o.Name != "name_300");
} // }
//
[Fact] // [Fact]
public async Task ToList_OrderBy_Asc_Desc_Test() // public async Task ToList_OrderBy_Asc_Desc_Test()
{ // {
var modascs = await _virtualDbContext.Set<SysUserMod>().OrderBy(o => o.Age).ToShardingListAsync(); // var modascs = await _virtualDbContext.Set<SysUserMod>().OrderBy(o => o.Age).ToShardingListAsync();
Assert.Equal(1000, modascs.Count); // Assert.Equal(1000, modascs.Count);
var i = 1; // var i = 1;
foreach (var age in modascs) // foreach (var age in modascs)
{ // {
Assert.Equal(i, age.Age); // Assert.Equal(i, age.Age);
i++; // i++;
} // }
//
var moddescs = await _virtualDbContext.Set<SysUserMod>().OrderByDescending(o => o.Age).ToShardingListAsync(); // var moddescs = await _virtualDbContext.Set<SysUserMod>().OrderByDescending(o => o.Age).ToShardingListAsync();
Assert.Equal(1000, moddescs.Count); // Assert.Equal(1000, moddescs.Count);
var j = 1000; // var j = 1000;
foreach (var age in moddescs) // foreach (var age in moddescs)
{ // {
Assert.Equal(j, age.Age); // Assert.Equal(j, age.Age);
j--; // j--;
} // }
} // }
//
[Fact] // [Fact]
public async Task ToList_Id_In_Test() // public async Task ToList_Id_In_Test()
{ // {
var ids = new[] {"1", "2", "3", "4"}; // var ids = new[] {"1", "2", "3", "4"};
var sysUserMods = await _virtualDbContext.Set<SysUserMod>().Where(o => ids.Contains(o.Id)).ToShardingListAsync(); // var sysUserMods = await _virtualDbContext.Set<SysUserMod>().Where(o => ids.Contains(o.Id)).ToShardingListAsync();
foreach (var id in ids) // foreach (var id in ids)
{ // {
Assert.Contains(sysUserMods, o => o.Id == id); // Assert.Contains(sysUserMods, o => o.Id == id);
} // }
//
Assert.DoesNotContain(sysUserMods, o => o.Age > 4); // Assert.DoesNotContain(sysUserMods, o => o.Age > 4);
} // }
//
[Fact] // [Fact]
public async Task ToList_Id_Eq_Test() // public async Task ToList_Id_Eq_Test()
{ // {
var mods = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "3").ToShardingListAsync(); // var mods = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "3").ToShardingListAsync();
Assert.Single(mods); // Assert.Single(mods);
Assert.Equal("3", mods[0].Id); // Assert.Equal("3", mods[0].Id);
} // }
//
[Fact] // [Fact]
public async Task ToList_Id_Not_Eq_Test() // public async Task ToList_Id_Not_Eq_Test()
{ // {
var mods = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id != "3").ToShardingListAsync(); // var mods = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id != "3").ToShardingListAsync();
Assert.Equal(999, mods.Count); // Assert.Equal(999, mods.Count);
Assert.DoesNotContain(mods, o => o.Id == "3"); // Assert.DoesNotContain(mods, o => o.Id == "3");
} // }
//
[Fact] // [Fact]
public async Task ToList_Id_Not_Eq_Skip_Test() // public async Task ToList_Id_Not_Eq_Skip_Test()
{ // {
var mods = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id != "3").OrderBy(o => o.Age).Skip(2).ToShardingListAsync(); // var mods = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id != "3").OrderBy(o => o.Age).Skip(2).ToShardingListAsync();
Assert.Equal(997, mods.Count); // Assert.Equal(997, mods.Count);
Assert.DoesNotContain(mods, o => o.Id == "3"); // Assert.DoesNotContain(mods, o => o.Id == "3");
Assert.Equal(4, mods[0].Age); // Assert.Equal(4, mods[0].Age);
Assert.Equal(5, mods[1].Age); // Assert.Equal(5, mods[1].Age);
//
var modsDesc = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id != "3").OrderByDescending(o => o.Age).Skip(13).ToShardingListAsync(); // var modsDesc = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id != "3").OrderByDescending(o => o.Age).Skip(13).ToShardingListAsync();
Assert.Equal(986, modsDesc.Count); // Assert.Equal(986, modsDesc.Count);
Assert.DoesNotContain(mods, o => o.Id == "3"); // Assert.DoesNotContain(mods, o => o.Id == "3");
Assert.Equal(987, modsDesc[0].Age); // Assert.Equal(987, modsDesc[0].Age);
Assert.Equal(986, modsDesc[1].Age); // Assert.Equal(986, modsDesc[1].Age);
} // }
//
[Fact] // [Fact]
public async Task ToList_Name_Eq_Test() // public async Task ToList_Name_Eq_Test()
{ // {
var mods = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name == "name_3").ToShardingListAsync(); // var mods = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name == "name_3").ToShardingListAsync();
Assert.Single(mods); // Assert.Single(mods);
Assert.Equal("3", mods[0].Id); // Assert.Equal("3", mods[0].Id);
} // }
//
[Fact] // [Fact]
public async Task ToList_Id_Eq_Not_In_Db_Test() // public async Task ToList_Id_Eq_Not_In_Db_Test()
{ // {
var mods = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "1001").ToShardingListAsync(); // var mods = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "1001").ToShardingListAsync();
Assert.Empty(mods); // Assert.Empty(mods);
} // }
//
[Fact] // [Fact]
public async Task ToList_Name_Eq_Not_In_Db_Test() // public async Task ToList_Name_Eq_Not_In_Db_Test()
{ // {
var mods = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name == "name_1001").ToShardingListAsync(); // var mods = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name == "name_1001").ToShardingListAsync();
Assert.Empty(mods); // Assert.Empty(mods);
} // }
//
[Fact] // [Fact]
public async Task FirstOrDefault_Order_By_Id_Test() // public async Task FirstOrDefault_Order_By_Id_Test()
{ // {
var sysUserModAge = await _virtualDbContext.Set<SysUserMod>().OrderBy(o => o.Age).ShardingFirstOrDefaultAsync(); // var sysUserModAge = await _virtualDbContext.Set<SysUserMod>().OrderBy(o => o.Age).ShardingFirstOrDefaultAsync();
Assert.True(sysUserModAge != null && sysUserModAge.Id == "1"); // Assert.True(sysUserModAge != null && sysUserModAge.Id == "1");
var sysUserModAgeDesc = await _virtualDbContext.Set<SysUserMod>().OrderByDescending(o => o.Age).ShardingFirstOrDefaultAsync(); // var sysUserModAgeDesc = await _virtualDbContext.Set<SysUserMod>().OrderByDescending(o => o.Age).ShardingFirstOrDefaultAsync();
Assert.True(sysUserModAgeDesc != null && sysUserModAgeDesc.Id == "1000"); // Assert.True(sysUserModAgeDesc != null && sysUserModAgeDesc.Id == "1000");
var sysUserMod = await _virtualDbContext.Set<SysUserMod>().OrderBy(o => o.Id).ShardingFirstOrDefaultAsync(); // var sysUserMod = await _virtualDbContext.Set<SysUserMod>().OrderBy(o => o.Id).ShardingFirstOrDefaultAsync();
Assert.True(sysUserMod != null && sysUserMod.Id == "1"); // Assert.True(sysUserMod != null && sysUserMod.Id == "1");
//
var sysUserModDesc = await _virtualDbContext.Set<SysUserMod>().OrderByDescending(o => o.Id).ShardingFirstOrDefaultAsync(); // var sysUserModDesc = await _virtualDbContext.Set<SysUserMod>().OrderByDescending(o => o.Id).ShardingFirstOrDefaultAsync();
Assert.True(sysUserModDesc != null && sysUserModDesc.Id == "999"); // Assert.True(sysUserModDesc != null && sysUserModDesc.Id == "999");
} // }
//
[Fact] // [Fact]
public async Task FirstOrDefault2() // public async Task FirstOrDefault2()
{ // {
var sysUserMod = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "1").ShardingFirstOrDefaultAsync(); // var sysUserMod = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "1").ShardingFirstOrDefaultAsync();
Assert.NotNull(sysUserMod); // Assert.NotNull(sysUserMod);
Assert.True(sysUserMod.Id == "1"); // Assert.True(sysUserMod.Id == "1");
} // }
//
[Fact] // [Fact]
public async Task FirstOrDefault3() // public async Task FirstOrDefault3()
{ // {
var sysUserMod = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name == "name_2").ShardingFirstOrDefaultAsync(); // var sysUserMod = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name == "name_2").ShardingFirstOrDefaultAsync();
Assert.NotNull(sysUserMod); // Assert.NotNull(sysUserMod);
Assert.Equal("2", sysUserMod.Id); // Assert.Equal("2", sysUserMod.Id);
} // }
//
[Fact] // [Fact]
public async Task FirstOrDefault4() // public async Task FirstOrDefault4()
{ // {
var sysUserMod = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id != "1").ShardingFirstOrDefaultAsync(); // var sysUserMod = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id != "1").ShardingFirstOrDefaultAsync();
Assert.NotNull(sysUserMod); // Assert.NotNull(sysUserMod);
Assert.True(sysUserMod.Id != "1"); // Assert.True(sysUserMod.Id != "1");
} // }
//
[Fact] // [Fact]
public async Task FirstOrDefault5() // public async Task FirstOrDefault5()
{ // {
var sysUserMod = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name == "name_1001").ShardingFirstOrDefaultAsync(); // var sysUserMod = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name == "name_1001").ShardingFirstOrDefaultAsync();
Assert.Null(sysUserMod); // Assert.Null(sysUserMod);
} // }
//
[Fact] // [Fact]
public async Task Count_Test() // public async Task Count_Test()
{ // {
var a = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name == "name_1000").ShardingCountAsync(); // var a = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name == "name_1000").ShardingCountAsync();
Assert.Equal(1, a); // Assert.Equal(1, a);
var b = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name != "name_1000").ShardingCountAsync(); // var b = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name != "name_1000").ShardingCountAsync();
Assert.Equal(999, b); // Assert.Equal(999, b);
} // }
//
[Fact] // [Fact]
public async Task Sum_Test() // public async Task Sum_Test()
{ // {
var a = await _virtualDbContext.Set<SysUserMod>().ShardingSumAsync(o => o.Age); // var a = await _virtualDbContext.Set<SysUserMod>().ShardingSumAsync(o => o.Age);
var expected = 0; // var expected = 0;
for (int i = 1; i <= 1000; i++) // for (int i = 1; i <= 1000; i++)
{ // {
expected += i; // expected += i;
} // }
//
Assert.Equal(expected, a); // Assert.Equal(expected, a);
var b = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name != "name_1000").ShardingSumAsync(o => o.Age); // var b = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name != "name_1000").ShardingSumAsync(o => o.Age);
Assert.Equal(expected - 1000, b); // Assert.Equal(expected - 1000, b);
} // }
//
[Fact] // [Fact]
public async Task Max_Test() // public async Task Max_Test()
{ // {
var a = await _virtualDbContext.Set<SysUserMod>().ShardingMaxAsync(o => o.Age); // var a = await _virtualDbContext.Set<SysUserMod>().ShardingMaxAsync(o => o.Age);
Assert.Equal(1000, a); // Assert.Equal(1000, a);
var b = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name != "name_1000").ShardingMaxAsync(o => o.Age); // var b = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name != "name_1000").ShardingMaxAsync(o => o.Age);
Assert.Equal(999, b); // Assert.Equal(999, b);
var c = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Age < 500).ShardingMaxAsync(o => o.Age); // var c = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Age < 500).ShardingMaxAsync(o => o.Age);
Assert.Equal(499, c); // Assert.Equal(499, c);
var e = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Age <= 500).ShardingMaxAsync(o => o.Age); // var e = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Age <= 500).ShardingMaxAsync(o => o.Age);
Assert.Equal(500, e); // Assert.Equal(500, e);
} // }
//
[Fact] // [Fact]
public async Task Max_Join_Test() // public async Task Max_Join_Test()
{ // {
var queryable = (from u in _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "300") // var queryable = (from u in _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "300")
join salary in _virtualDbContext.Set<SysUserSalary>() // join salary in _virtualDbContext.Set<SysUserSalary>()
on u.Id equals salary.UserId // on u.Id equals salary.UserId
select new // select new
{ // {
Salary = salary.Salary, // Salary = salary.Salary,
DateOfMonth = salary.DateOfMonth, // DateOfMonth = salary.DateOfMonth,
Name = u.Name // Name = u.Name
}); // });
var maxSalary = await queryable.ShardingMaxAsync(o => o.Salary); // var maxSalary = await queryable.ShardingMaxAsync(o => o.Salary);
Assert.Equal(1390000, maxSalary); // Assert.Equal(1390000, maxSalary);
} // }
//
[Fact] // [Fact]
public async Task Min_Test() // public async Task Min_Test()
{ // {
var a = await _virtualDbContext.Set<SysUserMod>().ShardingMinAsync(o => o.Age); // var a = await _virtualDbContext.Set<SysUserMod>().ShardingMinAsync(o => o.Age);
Assert.Equal(1, a); // Assert.Equal(1, a);
var b = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name != "name_1").ShardingMinAsync(o => o.Age); // var b = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name != "name_1").ShardingMinAsync(o => o.Age);
Assert.Equal(2, b); // Assert.Equal(2, b);
var c = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Age > 500).ShardingMinAsync(o => o.Age); // var c = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Age > 500).ShardingMinAsync(o => o.Age);
Assert.Equal(501, c); // Assert.Equal(501, c);
var e = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Age >= 500).ShardingMinAsync(o => o.Age); // var e = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Age >= 500).ShardingMinAsync(o => o.Age);
Assert.Equal(500, e); // Assert.Equal(500, e);
} // }
//
[Fact] // [Fact]
public async Task Any_Test() // public async Task Any_Test()
{ // {
var a = await _virtualDbContext.Set<SysUserMod>().ShardingAnyAsync(o => o.Age == 100); // var a = await _virtualDbContext.Set<SysUserMod>().ShardingAnyAsync(o => o.Age == 100);
Assert.True(a); // Assert.True(a);
var b = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name != "name_1").ShardingAnyAsync(o => o.Age == 1); // var b = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Name != "name_1").ShardingAnyAsync(o => o.Age == 1);
Assert.False(b); // Assert.False(b);
var c = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Age > 500).ShardingAnyAsync(o => o.Age <= 500); // var c = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Age > 500).ShardingAnyAsync(o => o.Age <= 500);
Assert.False(c); // Assert.False(c);
var e = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Age >= 500).ShardingAnyAsync(o => o.Age <= 500); // var e = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Age >= 500).ShardingAnyAsync(o => o.Age <= 500);
Assert.True(e); // Assert.True(e);
} // }
//
[Fact] // [Fact]
public async Task Group_Test() // public async Task Group_Test()
{ // {
var ids = new[] {"200", "300"}; // var ids = new[] {"200", "300"};
var dateOfMonths = new[] {202111, 202110}; // var dateOfMonths = new[] {202111, 202110};
var group = await (from u in _virtualDbContext.Set<SysUserSalary>() // var group = await (from u in _virtualDbContext.Set<SysUserSalary>()
.Where(o => ids.Contains(o.UserId) && dateOfMonths.Contains(o.DateOfMonth)) // .Where(o => ids.Contains(o.UserId) && dateOfMonths.Contains(o.DateOfMonth))
group u by new // group u by new
{ // {
UId = u.UserId // UId = u.UserId
} // }
into g // into g
select new // select new
{ // {
GroupUserId = g.Key.UId, // GroupUserId = g.Key.UId,
Count = g.Count(), // Count = g.Count(),
TotalSalary = g.Sum(o => o.Salary), // TotalSalary = g.Sum(o => o.Salary),
AvgSalary = g.Average(o => o.Salary), // AvgSalary = g.Average(o => o.Salary),
AvgSalaryDecimal = g.Average(o => o.SalaryDecimal), // AvgSalaryDecimal = g.Average(o => o.SalaryDecimal),
MinSalary = g.Min(o => o.Salary), // MinSalary = g.Min(o => o.Salary),
MaxSalary = g.Max(o => o.Salary) // MaxSalary = g.Max(o => o.Salary)
}).ToShardingListAsync(); // }).ToShardingListAsync();
Assert.Equal(2, group.Count); // Assert.Equal(2, group.Count);
Assert.Equal(2, group[0].Count); // Assert.Equal(2, group[0].Count);
Assert.Equal(2260000, group[0].TotalSalary); // Assert.Equal(2260000, group[0].TotalSalary);
Assert.Equal(1130000, group[0].AvgSalary); // Assert.Equal(1130000, group[0].AvgSalary);
Assert.Equal(11300, group[0].AvgSalaryDecimal); // Assert.Equal(11300, group[0].AvgSalaryDecimal);
Assert.Equal(1120000, group[0].MinSalary); // Assert.Equal(1120000, group[0].MinSalary);
Assert.Equal(1140000, group[0].MaxSalary); // Assert.Equal(1140000, group[0].MaxSalary);
} // }
[Fact] // [Fact]
public async Task Group_API_Test() // public async Task Group_API_Test()
{ // {
var ids = new[] {"200", "300"}; // var ids = new[] {"200", "300"};
var dateOfMonths = new[] {202111, 202110}; // var dateOfMonths = new[] {202111, 202110};
var group = await _virtualDbContext.Set<SysUserSalary>() // var group = await _virtualDbContext.Set<SysUserSalary>()
.Where(o => ids.Contains(o.UserId) && dateOfMonths.Contains(o.DateOfMonth)) // .Where(o => ids.Contains(o.UserId) && dateOfMonths.Contains(o.DateOfMonth))
.ShardingGroupByAsync(g => new {UId = g.UserId}, g => new // .ShardingGroupByAsync(g => new {UId = g.UserId}, g => new
{ // {
//
GroupUserId = g.Key.UId, // GroupUserId = g.Key.UId,
Count = g.Count(), // Count = g.Count(),
TotalSalary = g.Sum(o => o.Salary), // TotalSalary = g.Sum(o => o.Salary),
AvgSalary = g.Average(o => o.Salary), // AvgSalary = g.Average(o => o.Salary),
AvgSalaryDecimal = g.Average(o => o.SalaryDecimal), // AvgSalaryDecimal = g.Average(o => o.SalaryDecimal),
MinSalary = g.Min(o => o.Salary), // MinSalary = g.Min(o => o.Salary),
MaxSalary = g.Max(o => o.Salary) // MaxSalary = g.Max(o => o.Salary)
}); // });
Assert.Equal(2, group.Count); // Assert.Equal(2, group.Count);
Assert.Equal(2, group[0].Count); // Assert.Equal(2, group[0].Count);
Assert.Equal(2260000, group[0].TotalSalary); // Assert.Equal(2260000, group[0].TotalSalary);
Assert.Equal(1130000, group[0].AvgSalary); // Assert.Equal(1130000, group[0].AvgSalary);
Assert.Equal(11300, group[0].AvgSalaryDecimal); // Assert.Equal(11300, group[0].AvgSalaryDecimal);
Assert.Equal(1120000, group[0].MinSalary); // Assert.Equal(1120000, group[0].MinSalary);
Assert.Equal(1140000, group[0].MaxSalary); // Assert.Equal(1140000, group[0].MaxSalary);
} // }
// [Fact] // // [Fact]
// public async Task UpdateColumn() // // public async Task UpdateColumn()
// { // // {
// var item = await _virtualDbContext.Set<SysUserMod>().Where(o=>o.Id=="147").ShardingFirstOrDefaultAsync(); // // var item = await _virtualDbContext.Set<SysUserMod>().Where(o=>o.Id=="147").ShardingFirstOrDefaultAsync();
// var oldName = item.Name; // // var oldName = item.Name;
// var oldAge = item.Age; // // var oldAge = item.Age;
// var newName = $"test_{new Random().Next(0, 99999)}"; // // var newName = $"test_{new Random().Next(0, 99999)}";
// var newAge = new Random().Next(0, 99999); // // var newAge = new Random().Next(0, 99999);
// item.Name = newName; // // item.Name = newName;
// item.Age = newAge; // // item.Age = newAge;
// _virtualDbContext.UpdateColumns(item,o=>new {o.Name}); // // _virtualDbContext.UpdateColumns(item,o=>new {o.Name});
// await _virtualDbContext.SaveChangesAsync(); // // await _virtualDbContext.SaveChangesAsync();
// // //
// var newItem = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "147").ShardingFirstOrDefaultAsync(); // // var newItem = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "147").ShardingFirstOrDefaultAsync();
// Assert.Equal(newName, newItem.Name); // // Assert.Equal(newName, newItem.Name);
// Assert.NotEqual(oldName, newItem.Name); // // Assert.NotEqual(oldName, newItem.Name);
// Assert.NotEqual(newAge, newItem.Age); // // Assert.NotEqual(newAge, newItem.Age);
// Assert.Equal(oldAge, newItem.Age); // // Assert.Equal(oldAge, newItem.Age);
// } // // }
// [Fact] // // [Fact]
// public async Task UpdateIgnoreColumn() // // public async Task UpdateIgnoreColumn()
// { // // {
// var item = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "153").ShardingFirstOrDefaultAsync(); // // var item = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "153").ShardingFirstOrDefaultAsync();
// var oldName = item.Name; // // var oldName = item.Name;
// var oldAge = item.Age; // // var oldAge = item.Age;
// var newName = $"test_{new Random().Next(0, 99999)}"; // // var newName = $"test_{new Random().Next(0, 99999)}";
// var newAge = new Random().Next(0, 99999); // // var newAge = new Random().Next(0, 99999);
// item.Name = newName; // // item.Name = newName;
// item.Age = newAge; // // item.Age = newAge;
// _virtualDbContext.UpdateWithOutIgnoreColumns(item, o => new { o.Name }); // // _virtualDbContext.UpdateWithOutIgnoreColumns(item, o => new { o.Name });
// await _virtualDbContext.SaveChangesAsync(); // // await _virtualDbContext.SaveChangesAsync();
// // //
// var newItem = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "153").ShardingFirstOrDefaultAsync(); // // var newItem = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "153").ShardingFirstOrDefaultAsync();
// Assert.NotEqual(newName, newItem.Name); // // Assert.NotEqual(newName, newItem.Name);
// Assert.Equal(oldName, newItem.Name); // // Assert.Equal(oldName, newItem.Name);
// Assert.Equal(newAge, newItem.Age); // // Assert.Equal(newAge, newItem.Age);
// Assert.NotEqual(oldAge, newItem.Age); // // Assert.NotEqual(oldAge, newItem.Age);
// } // // }
} // }
} // }

View File

@ -7,11 +7,7 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using ShardingCore; using ShardingCore;
using ShardingCore.DbContexts.VirtualDbContexts;
using ShardingCore.Extensions;
using ShardingCore.SqlServer;
using ShardingCoreTestSqlServer3x.Domain.Entities; using ShardingCoreTestSqlServer3x.Domain.Entities;
using ShardingCoreTestSqlServer3x.Shardings;
namespace ShardingCoreTestSqlServer3x namespace ShardingCoreTestSqlServer3x
{ {
@ -39,21 +35,21 @@ namespace ShardingCoreTestSqlServer3x
// ConfigureServices(HostBuilderContext hostBuilderContext, IServiceCollection services) // ConfigureServices(HostBuilderContext hostBuilderContext, IServiceCollection services)
public void ConfigureServices(IServiceCollection services, HostBuilderContext hostBuilderContext) public void ConfigureServices(IServiceCollection services, HostBuilderContext hostBuilderContext)
{ {
services.AddShardingSqlServer(o => // services.AddShardingSqlServer(o =>
{ // {
o.EnsureCreatedWithOutShardingTable = true; // o.EnsureCreatedWithOutShardingTable = true;
o.CreateShardingTableOnStart = true; // o.CreateShardingTableOnStart = true;
o.UseShardingDbContext<DefaultDbContext>(dbConfig => // o.UseShardingDbContext<DefaultDbContext>(dbConfig =>
{ // {
dbConfig.AddShardingTableRoute<SysUserModVirtualTableRoute>(); // dbConfig.AddShardingTableRoute<SysUserModVirtualTableRoute>();
dbConfig.AddShardingTableRoute<SysUserSalaryVirtualTableRoute>(); // dbConfig.AddShardingTableRoute<SysUserSalaryVirtualTableRoute>();
}); // });
//o.AddDataSourceVirtualRoute<>(); // //o.AddDataSourceVirtualRoute<>();
//
}); // });
services.AddDbContext<DefaultDbContext>(o => // services.AddDbContext<DefaultDbContext>(o =>
o.UseSqlServer(hostBuilderContext.Configuration.GetSection("SqlServer")["ConnectionString"]) // o.UseSqlServer(hostBuilderContext.Configuration.GetSection("SqlServer")["ConnectionString"])
.UseShardingSqlServerUpdateSqlGenerator()); // .UseShardingSqlServerUpdateSqlGenerator());
} }
// 可以添加要用到的方法参数,会自动从注册的服务中获取服务实例,类似于 asp.net core 里 Configure 方法 // 可以添加要用到的方法参数,会自动从注册的服务中获取服务实例,类似于 asp.net core 里 Configure 方法
@ -75,7 +71,7 @@ namespace ShardingCoreTestSqlServer3x
using (var scope = serviceProvider.CreateScope()) using (var scope = serviceProvider.CreateScope())
{ {
var virtualDbContext = scope.ServiceProvider.GetService<DefaultDbContext>(); var virtualDbContext = scope.ServiceProvider.GetService<DefaultDbContext>();
if (!await virtualDbContext.Set<SysUserMod>().ShardingAnyAsync(o => true)) if (!await virtualDbContext.Set<SysUserMod>().AnyAsync(o => true))
{ {
var ids = Enumerable.Range(1, 1000); var ids = Enumerable.Range(1, 1000);
var userMods = new List<SysUserMod>(); var userMods = new List<SysUserMod>();