完成分表+分库的全部使用和demo编写并且发布x.3.1.28
This commit is contained in:
parent
579c5cc6db
commit
ac83780b67
|
@ -49,6 +49,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Sample.Migrations", "sample
|
|||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sample.SqlServerShardingTable", "samples\Sample.SqlServerShardingTable\Sample.SqlServerShardingTable.csproj", "{88FA5615-1BAA-4021-87EF-9D4A60257FE4}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sample.SqlServerShardingAll", "samples\Sample.SqlServerShardingAll\Sample.SqlServerShardingAll.csproj", "{FD2C6D03-8D6D-4C1C-B534-4C785A4B1B06}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
|
@ -123,6 +125,10 @@ Global
|
|||
{88FA5615-1BAA-4021-87EF-9D4A60257FE4}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{88FA5615-1BAA-4021-87EF-9D4A60257FE4}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{88FA5615-1BAA-4021-87EF-9D4A60257FE4}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{FD2C6D03-8D6D-4C1C-B534-4C785A4B1B06}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{FD2C6D03-8D6D-4C1C-B534-4C785A4B1B06}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{FD2C6D03-8D6D-4C1C-B534-4C785A4B1B06}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{FD2C6D03-8D6D-4C1C-B534-4C785A4B1B06}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
@ -145,6 +151,7 @@ Global
|
|||
{68A9F118-EF0A-4D03-8845-77D084561A28} = {EB1C9149-78C9-4D99-BE3F-B80FE2015E96}
|
||||
{648DCBBE-BE8F-4EAC-8367-FE7BC558DA8C} = {EDF8869A-C1E1-491B-BC9F-4A33F4DE1C73}
|
||||
{88FA5615-1BAA-4021-87EF-9D4A60257FE4} = {EDF8869A-C1E1-491B-BC9F-4A33F4DE1C73}
|
||||
{FD2C6D03-8D6D-4C1C-B534-4C785A4B1B06} = {EDF8869A-C1E1-491B-BC9F-4A33F4DE1C73}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {8C07A667-E8B4-43C7-8053-721584BAD291}
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
:start
|
||||
::定义版本
|
||||
set EFCORE2=2.3.1.27
|
||||
set EFCORE3=3.3.1.27
|
||||
set EFCORE5=5.3.1.27
|
||||
set EFCORE2=2.3.1.28
|
||||
set EFCORE3=3.3.1.28
|
||||
set EFCORE5=5.3.1.28
|
||||
|
||||
::删除所有bin与obj下的文件
|
||||
@echo off
|
||||
|
|
|
@ -0,0 +1,98 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Sample.SqlServerShardingAll.Entities;
|
||||
|
||||
namespace Sample.SqlServerShardingAll.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("[controller]/[action]")]
|
||||
public class TestController : ControllerBase
|
||||
{
|
||||
private readonly MyDbContext _myDbContext;
|
||||
|
||||
public TestController(MyDbContext myDbContext)
|
||||
{
|
||||
_myDbContext = myDbContext;
|
||||
}
|
||||
public async Task<IActionResult> Query()
|
||||
{
|
||||
var sysUser =await _myDbContext.Set<SysUser>().Where(o=>o.Id=="1").FirstOrDefaultAsync();
|
||||
var sysUserA1 =await _myDbContext.Set<SysUser>().Where(o=>o.Id=="1" && o.Area == "A").FirstOrDefaultAsync();
|
||||
var dateTime = new DateTime(2021,3,5);
|
||||
var order = await _myDbContext.Set<Order>().Where(o=>o.CreationTime>= dateTime).OrderBy(o=>o.CreationTime).FirstOrDefaultAsync();
|
||||
var orderIdOne = await _myDbContext.Set<Order>().FirstOrDefaultAsync(o => o.Id == "3");
|
||||
|
||||
|
||||
var sysUsers = await _myDbContext.Set<SysUser>().Where(o => o.Id == "1" || o.Id=="6").ToListAsync();
|
||||
|
||||
return Ok(new object[]
|
||||
{
|
||||
sysUser,
|
||||
order,
|
||||
orderIdOne,
|
||||
sysUsers
|
||||
});
|
||||
}
|
||||
public async Task<IActionResult> QueryJoin()
|
||||
{
|
||||
var begin = new DateTime(2021, 3, 2);
|
||||
var end = new DateTime(2021, 5, 9);
|
||||
var sql1 = from user in _myDbContext.Set<SysUser>().Where(o => o.Id == "1" || o.Id == "6")
|
||||
join order in _myDbContext.Set<Order>().Where(o=>o.CreationTime>=begin&&o.CreationTime<=end)
|
||||
on user.Id equals order.Payer
|
||||
select new
|
||||
{
|
||||
user.Id,
|
||||
user.Name,
|
||||
user.Area,
|
||||
OrderId = order.Id,
|
||||
order.Payer,
|
||||
order.CreationTime
|
||||
};
|
||||
return Ok(await sql1.ToListAsync());
|
||||
}
|
||||
public async Task<IActionResult> QueryJoin2()
|
||||
{
|
||||
var begin = new DateTime(2021, 3, 2);
|
||||
var end = new DateTime(2021, 5, 9);
|
||||
var sql1 = from user in _myDbContext.Set<SysUser>().Where(o => (o.Id == "1" || o.Id == "6")&&o.Area=="A")
|
||||
join order in _myDbContext.Set<Order>().Where(o => o.CreationTime >= begin && o.CreationTime <= end)
|
||||
on user.Id equals order.Payer
|
||||
select new
|
||||
{
|
||||
user.Id,
|
||||
user.Name,
|
||||
user.Area,
|
||||
OrderId = order.Id,
|
||||
order.Payer,
|
||||
order.CreationTime
|
||||
};
|
||||
return Ok(await sql1.ToListAsync());
|
||||
}
|
||||
public async Task<IActionResult> Update()
|
||||
{
|
||||
var sysUser = await _myDbContext.Set<SysUser>().Where(o => o.Id == "1").FirstOrDefaultAsync();
|
||||
sysUser.Name = "new name";
|
||||
var i=await _myDbContext.SaveChangesAsync();
|
||||
return Ok(i);
|
||||
}
|
||||
public async Task<IActionResult> Update1()
|
||||
{
|
||||
var sysUser = await _myDbContext.Set<SysUser>().AsNoTracking().Where(o => o.Id == "1").FirstOrDefaultAsync();
|
||||
sysUser.Name = "new name";
|
||||
_myDbContext.Update(sysUser);
|
||||
var i = await _myDbContext.SaveChangesAsync();
|
||||
return Ok(i);
|
||||
}
|
||||
public async Task<IActionResult> Delete()
|
||||
{
|
||||
var sysUser = await _myDbContext.Set<SysUser>().Where(o => o.Id == "9").FirstOrDefaultAsync();
|
||||
_myDbContext.Remove(sysUser);
|
||||
var i = await _myDbContext.SaveChangesAsync();
|
||||
return Ok(i);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Sample.SqlServerShardingAll.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("[controller]")]
|
||||
public class WeatherForecastController : ControllerBase
|
||||
{
|
||||
private static readonly string[] Summaries = new[]
|
||||
{
|
||||
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
|
||||
};
|
||||
|
||||
private readonly ILogger<WeatherForecastController> _logger;
|
||||
|
||||
public WeatherForecastController(ILogger<WeatherForecastController> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public IEnumerable<WeatherForecast> Get()
|
||||
{
|
||||
var rng = new Random();
|
||||
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
|
||||
{
|
||||
Date = DateTime.Now.AddDays(index),
|
||||
TemperatureC = rng.Next(-20, 55),
|
||||
Summary = Summaries[rng.Next(Summaries.Length)]
|
||||
})
|
||||
.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
using System;
|
||||
|
||||
namespace Sample.SqlServerShardingAll.Entities
|
||||
{
|
||||
/// <summary>
|
||||
/// order table
|
||||
/// </summary>
|
||||
public class Order
|
||||
{
|
||||
/// <summary>
|
||||
/// order Id
|
||||
/// </summary>
|
||||
public string Id { get; set; }
|
||||
/// <summary>
|
||||
/// payer id
|
||||
/// </summary>
|
||||
public string Payer { get; set; }
|
||||
/// <summary>
|
||||
/// pay money cent
|
||||
/// </summary>
|
||||
public long Money { get; set; }
|
||||
/// <summary>
|
||||
/// area
|
||||
/// </summary>
|
||||
public string Area { get; set; }
|
||||
/// <summary>
|
||||
/// order status
|
||||
/// </summary>
|
||||
public OrderStatusEnum OrderStatus { get; set; }
|
||||
/// <summary>
|
||||
/// CreationTime
|
||||
/// </summary>
|
||||
public DateTime CreationTime { get; set; }
|
||||
}
|
||||
public enum OrderStatusEnum
|
||||
{
|
||||
NoPay=1,
|
||||
Paying=2,
|
||||
Payed=3,
|
||||
PayFail=4
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
namespace Sample.SqlServerShardingAll.Entities
|
||||
{
|
||||
/// <summary>
|
||||
/// user table
|
||||
/// </summary>
|
||||
public class SysUser
|
||||
{
|
||||
/// <summary>
|
||||
/// user id
|
||||
/// </summary>
|
||||
public string Id { get; set; }
|
||||
/// <summary>
|
||||
/// user name
|
||||
/// </summary>
|
||||
public string Name { get; set; }
|
||||
/// <summary>
|
||||
/// area
|
||||
/// </summary>
|
||||
public string Area { get; set; }
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
using Microsoft.EntityFrameworkCore;
|
||||
using Sample.SqlServerShardingAll.Entities;
|
||||
using ShardingCore.Core.VirtualRoutes.TableRoutes.RouteTails.Abstractions;
|
||||
using ShardingCore.Sharding;
|
||||
using ShardingCore.Sharding.Abstractions;
|
||||
|
||||
namespace Sample.SqlServerShardingAll
|
||||
{
|
||||
public class MyDbContext:AbstractShardingDbContext,IShardingTableDbContext
|
||||
{
|
||||
public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
|
||||
{
|
||||
}
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
base.OnModelCreating(modelBuilder);
|
||||
modelBuilder.Entity<Order>(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<int>();
|
||||
entity.ToTable(nameof(Order));
|
||||
});
|
||||
modelBuilder.Entity<SysUser>(entity =>
|
||||
{
|
||||
entity.HasKey(o => o.Id);
|
||||
entity.Property(o => o.Id).IsRequired().IsUnicode(false).HasMaxLength(50);
|
||||
entity.Property(o=>o.Name).IsRequired().IsUnicode(false).HasMaxLength(50);
|
||||
entity.Property(o=>o.Area).IsRequired().IsUnicode(false).HasMaxLength(50);
|
||||
entity.ToTable(nameof(SysUser));
|
||||
});
|
||||
}
|
||||
|
||||
public IRouteTail RouteTail { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Sample.SqlServerShardingAll
|
||||
{
|
||||
public class Program
|
||||
{
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
CreateHostBuilder(args).Build().Run();
|
||||
}
|
||||
|
||||
public static IHostBuilder CreateHostBuilder(string[] args) =>
|
||||
Host.CreateDefaultBuilder(args)
|
||||
.ConfigureWebHostDefaults(webBuilder =>
|
||||
{
|
||||
webBuilder.UseStartup<Startup>();
|
||||
});
|
||||
}
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
{
|
||||
"$schema": "http://json.schemastore.org/launchsettings.json",
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:11354",
|
||||
"sslPort": 0
|
||||
}
|
||||
},
|
||||
"profiles": {
|
||||
"Sample.SqlServerShardingAll": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": "true",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "weatherforecast",
|
||||
"applicationUrl": "http://localhost:5000",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net5.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.11" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\ShardingCore\ShardingCore.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
|
@ -0,0 +1,97 @@
|
|||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
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.SqlServerShardingAll.VirtualDataSourceRoutes;
|
||||
using Sample.SqlServerShardingAll.VirtualTableRoutes;
|
||||
using ShardingCore;
|
||||
|
||||
namespace Sample.SqlServerShardingAll
|
||||
{
|
||||
public class Startup
|
||||
{
|
||||
public static readonly ILoggerFactory efLogger = LoggerFactory.Create(builder =>
|
||||
{
|
||||
builder.AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information).AddConsole();
|
||||
});
|
||||
public Startup(IConfiguration configuration)
|
||||
{
|
||||
Configuration = configuration;
|
||||
}
|
||||
|
||||
public IConfiguration Configuration { get; }
|
||||
|
||||
// This method gets called by the runtime. Use this method to add services to the container.
|
||||
public void ConfigureServices(IServiceCollection services)
|
||||
{
|
||||
|
||||
services.AddControllers();
|
||||
|
||||
services.AddShardingDbContext<MyDbContext>((conStr, builder) =>
|
||||
{
|
||||
builder.UseSqlServer(conStr).UseLoggerFactory(efLogger);
|
||||
}).Begin(op =>
|
||||
{
|
||||
op.AutoTrackEntity = true;
|
||||
//如果您使用code-first建议选择false
|
||||
op.CreateShardingTableOnStart = true;
|
||||
//如果您使用code-first建议修改为fsle
|
||||
op.EnsureCreatedWithOutShardingTable = true;
|
||||
}).AddShardingTransaction((connection, builder) =>
|
||||
{
|
||||
builder.UseSqlServer(connection).UseLoggerFactory(efLogger);
|
||||
}).AddDefaultDataSource("A",
|
||||
"Data Source=localhost;Initial Catalog=EFCoreShardingDataSourceTableDBA;Integrated Security=True;")
|
||||
.AddShardingDataSource(sp =>
|
||||
{
|
||||
return new Dictionary<string, string>()
|
||||
{
|
||||
{
|
||||
"B","Data Source=localhost;Initial Catalog=EFCoreShardingDataSourceTableDBB;Integrated Security=True;"
|
||||
},
|
||||
{
|
||||
"C","Data Source=localhost;Initial Catalog=EFCoreShardingDataSourceTableDBC;Integrated Security=True;"
|
||||
},
|
||||
};
|
||||
})
|
||||
.AddShardingDataSourceRoute(op =>
|
||||
{
|
||||
op.AddShardingDatabaseRoute<SysUserVirtualDataSourceRoute>();
|
||||
op.AddShardingDatabaseRoute<OrderVirtualDataSourceRoute>();
|
||||
}).AddShardingTableRoute(op =>
|
||||
{
|
||||
op.AddShardingTableRoute<SysUserVirtualTableRoute>();
|
||||
op.AddShardingTableRoute<OrderVirtualTableRoute>();
|
||||
}).End();
|
||||
}
|
||||
|
||||
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
|
||||
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
|
||||
{
|
||||
if (env.IsDevelopment())
|
||||
{
|
||||
app.UseDeveloperExceptionPage();
|
||||
}
|
||||
|
||||
//初始化ShardingCore
|
||||
app.UseShardingCore();
|
||||
app.UseRouting();
|
||||
|
||||
app.UseAuthorization();
|
||||
|
||||
app.UseEndpoints(endpoints =>
|
||||
{
|
||||
endpoints.MapControllers();
|
||||
});
|
||||
app.InitSeed();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,59 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Sample.SqlServerShardingAll.Entities;
|
||||
using ShardingCore.Bootstrapers;
|
||||
|
||||
namespace Sample.SqlServerShardingAll
|
||||
{
|
||||
public static class StartupExtension
|
||||
{
|
||||
public static void UseShardingCore(this IApplicationBuilder app)
|
||||
{
|
||||
app.ApplicationServices.GetRequiredService<IShardingBootstrapper>().Start();
|
||||
}
|
||||
public static void InitSeed(this IApplicationBuilder app)
|
||||
{
|
||||
using (var serviceScope = app.ApplicationServices.CreateScope())
|
||||
{
|
||||
var myDbContext = serviceScope.ServiceProvider.GetRequiredService<MyDbContext>();
|
||||
if (!myDbContext.Set<SysUser>().Any())
|
||||
{
|
||||
string[] areas = new string[] {"A","B","C" };
|
||||
List<SysUser> users = new List<SysUser>(10);
|
||||
for (int i = 0; i < 100; i++)
|
||||
{
|
||||
var uer=new SysUser()
|
||||
{
|
||||
Id = i.ToString(),
|
||||
Name = $"MyName{i}",
|
||||
Area = areas[new Random().Next(0,3)]
|
||||
};
|
||||
users.Add(uer);
|
||||
}
|
||||
List<Order> orders = new List<Order>(300);
|
||||
var begin = new DateTime(2021, 1, 1, 3, 3, 3);
|
||||
for (int i = 0; i < 300; i++)
|
||||
{
|
||||
var sysUser = users[i % 100];
|
||||
var order = new Order()
|
||||
{
|
||||
Id = i.ToString(),
|
||||
Payer = sysUser.Id,
|
||||
Money = 100+new Random().Next(100,3000),
|
||||
OrderStatus = (OrderStatusEnum)(i % 4 + 1),
|
||||
Area = sysUser.Area,
|
||||
CreationTime = begin.AddDays(i)
|
||||
};
|
||||
orders.Add(order);
|
||||
}
|
||||
myDbContext.AddRange(users);
|
||||
myDbContext.AddRange(orders);
|
||||
myDbContext.SaveChanges();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,60 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using Sample.SqlServerShardingAll.Entities;
|
||||
using ShardingCore.Core.EntityMetadatas;
|
||||
using ShardingCore.Core.VirtualRoutes;
|
||||
using ShardingCore.Core.VirtualRoutes.DataSourceRoutes.Abstractions;
|
||||
|
||||
namespace Sample.SqlServerShardingAll.VirtualDataSourceRoutes
|
||||
{
|
||||
public class OrderVirtualDataSourceRoute : AbstractShardingOperatorVirtualDataSourceRoute<Order, string>
|
||||
{
|
||||
private readonly List<string> _dataSources = new List<string>()
|
||||
{
|
||||
"A", "B", "C"
|
||||
};
|
||||
protected override string ConvertToShardingKey(object shardingKey)
|
||||
{
|
||||
return shardingKey?.ToString() ?? string.Empty;
|
||||
}
|
||||
//我们设置区域就是数据库
|
||||
public override string ShardingKeyToDataSourceName(object shardingKey)
|
||||
{
|
||||
return ConvertToShardingKey(shardingKey);
|
||||
}
|
||||
|
||||
public override List<string> GetAllDataSourceNames()
|
||||
{
|
||||
return _dataSources;
|
||||
}
|
||||
|
||||
public override bool AddDataSourceName(string dataSourceName)
|
||||
{
|
||||
if (_dataSources.Any(o => o == dataSourceName))
|
||||
return false;
|
||||
_dataSources.Add(dataSourceName);
|
||||
return true;
|
||||
}
|
||||
|
||||
protected override Expression<Func<string, bool>> GetRouteToFilter(string shardingKey, ShardingOperatorEnum shardingOperator)
|
||||
{
|
||||
|
||||
var t = ShardingKeyToDataSourceName(shardingKey);
|
||||
switch (shardingOperator)
|
||||
{
|
||||
case ShardingOperatorEnum.Equal: return tail => tail == t;
|
||||
default:
|
||||
{
|
||||
return tail => true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void Configure(EntityMetadataDataSourceBuilder<Order> builder)
|
||||
{
|
||||
builder.ShardingProperty(o => o.Area);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,60 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using Sample.SqlServerShardingAll.Entities;
|
||||
using ShardingCore.Core.EntityMetadatas;
|
||||
using ShardingCore.Core.VirtualRoutes;
|
||||
using ShardingCore.Core.VirtualRoutes.DataSourceRoutes.Abstractions;
|
||||
|
||||
namespace Sample.SqlServerShardingAll.VirtualDataSourceRoutes
|
||||
{
|
||||
public class SysUserVirtualDataSourceRoute : AbstractShardingOperatorVirtualDataSourceRoute<SysUser, string>
|
||||
{
|
||||
private readonly List<string> _dataSources = new List<string>()
|
||||
{
|
||||
"A", "B", "C"
|
||||
};
|
||||
protected override string ConvertToShardingKey(object shardingKey)
|
||||
{
|
||||
return shardingKey?.ToString() ?? string.Empty;
|
||||
}
|
||||
//我们设置区域就是数据库
|
||||
public override string ShardingKeyToDataSourceName(object shardingKey)
|
||||
{
|
||||
return ConvertToShardingKey(shardingKey);
|
||||
}
|
||||
|
||||
public override List<string> GetAllDataSourceNames()
|
||||
{
|
||||
return _dataSources;
|
||||
}
|
||||
|
||||
public override bool AddDataSourceName(string dataSourceName)
|
||||
{
|
||||
if (_dataSources.Any(o => o == dataSourceName))
|
||||
return false;
|
||||
_dataSources.Add(dataSourceName);
|
||||
return true;
|
||||
}
|
||||
|
||||
protected override Expression<Func<string, bool>> GetRouteToFilter(string shardingKey, ShardingOperatorEnum shardingOperator)
|
||||
{
|
||||
|
||||
var t = ShardingKeyToDataSourceName(shardingKey);
|
||||
switch (shardingOperator)
|
||||
{
|
||||
case ShardingOperatorEnum.Equal: return tail => tail == t;
|
||||
default:
|
||||
{
|
||||
return tail => true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void Configure(EntityMetadataDataSourceBuilder<SysUser> builder)
|
||||
{
|
||||
builder.ShardingProperty(o => o.Area);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
using System;
|
||||
using Sample.SqlServerShardingAll.Entities;
|
||||
using ShardingCore.Core.EntityMetadatas;
|
||||
using ShardingCore.VirtualRoutes.Months;
|
||||
|
||||
namespace Sample.SqlServerShardingAll.VirtualTableRoutes
|
||||
{
|
||||
public class OrderVirtualTableRoute:AbstractSimpleShardingMonthKeyDateTimeVirtualTableRoute<Order>
|
||||
{
|
||||
public override DateTime GetBeginTime()
|
||||
{
|
||||
return new DateTime(2021, 1, 1);
|
||||
}
|
||||
|
||||
public override void Configure(EntityMetadataTableBuilder<Order> builder)
|
||||
{
|
||||
builder.ShardingProperty(o => o.CreationTime);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
using Sample.SqlServerShardingAll.Entities;
|
||||
using ShardingCore.Core.EntityMetadatas;
|
||||
using ShardingCore.VirtualRoutes.Mods;
|
||||
|
||||
namespace Sample.SqlServerShardingAll.VirtualTableRoutes
|
||||
{
|
||||
public class SysUserVirtualTableRoute:AbstractSimpleShardingModKeyStringVirtualTableRoute<SysUser>
|
||||
{
|
||||
public SysUserVirtualTableRoute() : base(2, 3)
|
||||
{
|
||||
}
|
||||
|
||||
public override void Configure(EntityMetadataTableBuilder<SysUser> builder)
|
||||
{
|
||||
builder.ShardingProperty(o => o.Id);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
using System;
|
||||
|
||||
namespace Sample.SqlServerShardingAll
|
||||
{
|
||||
public class WeatherForecast
|
||||
{
|
||||
public DateTime Date { get; set; }
|
||||
|
||||
public int TemperatureC { get; set; }
|
||||
|
||||
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
|
||||
|
||||
public string Summary { get; set; }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft": "Warning",
|
||||
"Microsoft.Hosting.Lifetime": "Information"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft": "Warning",
|
||||
"Microsoft.Hosting.Lifetime": "Information"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
|
@ -6,7 +6,7 @@ using ShardingCore.Sharding.Abstractions;
|
|||
|
||||
namespace Sample.SqlServerShardingDataSource
|
||||
{
|
||||
public class MyDbContext:AbstractShardingDbContext,IShardingTableDbContext
|
||||
public class MyDbContext:AbstractShardingDbContext
|
||||
{
|
||||
public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
|
||||
{
|
||||
|
@ -34,6 +34,5 @@ namespace Sample.SqlServerShardingDataSource
|
|||
});
|
||||
}
|
||||
|
||||
public IRouteTail RouteTail { get; set; }
|
||||
}
|
||||
}
|
||||
|
|
|
@ -107,8 +107,17 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors
|
|||
}
|
||||
else
|
||||
{
|
||||
var connectionString = _actualConnectionStringManager.GetConnectionString(DataSourceName, true);
|
||||
_shardingDbContextOptionsBuilderConfig.UseDbContextOptionsBuilder(connectionString, dbContextOptionsBuilder);
|
||||
if (_dataSourceDbContexts.IsEmpty)
|
||||
{
|
||||
var connectionString = _actualConnectionStringManager.GetConnectionString(DataSourceName, true);
|
||||
_shardingDbContextOptionsBuilderConfig.UseDbContextOptionsBuilder(connectionString, dbContextOptionsBuilder);
|
||||
return dbContextOptionsBuilder.Options;
|
||||
}
|
||||
else
|
||||
{
|
||||
var dbConnection = _dataSourceDbContexts.First().Value.Database.GetDbConnection();
|
||||
_shardingDbContextOptionsBuilderConfig.UseDbContextOptionsBuilder(dbConnection, dbContextOptionsBuilder);
|
||||
}
|
||||
}
|
||||
_dbContextOptions = dbContextOptionsBuilder.Options;
|
||||
return _dbContextOptions;
|
||||
|
|
|
@ -182,15 +182,6 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors
|
|||
}
|
||||
}
|
||||
|
||||
|
||||
private void BeginTransaction()
|
||||
{
|
||||
foreach (var dbContextCache in _dbContextCaches)
|
||||
{
|
||||
dbContextCache.Value.NotifyTransaction();
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
|
|
|
@ -1,31 +0,0 @@
|
|||
//using System;
|
||||
//using System.Data;
|
||||
//using System.Threading;
|
||||
//using System.Threading.Tasks;
|
||||
//using Microsoft.EntityFrameworkCore;
|
||||
|
||||
//namespace ShardingCore.Sharding.ShardingTransactions
|
||||
//{
|
||||
// /*
|
||||
// * @Author: xjm
|
||||
// * @Description:
|
||||
// * @Date: 2021/9/6 8:41:50
|
||||
// * @Ver: 1.0
|
||||
// * @Email: 326308290@qq.com
|
||||
// */
|
||||
// public interface IShardingTransaction:IDisposable
|
||||
//#if !EFCORE2
|
||||
//,IAsyncDisposable
|
||||
//#endif
|
||||
// {
|
||||
// bool IsBeginTransaction();
|
||||
// void BeginTransaction(IsolationLevel isolationLevel = IsolationLevel.Unspecified);
|
||||
// void Use(string dataSourceName,DbContext dbContext);
|
||||
// void Rollback();
|
||||
// void Commit();
|
||||
//#if !EFCORE2
|
||||
// Task RollbackAsync(CancellationToken cancellationToken = new CancellationToken());
|
||||
// Task CommitAsync(CancellationToken cancellationToken = new CancellationToken());
|
||||
//#endif
|
||||
// }
|
||||
//}
|
|
@ -1,179 +0,0 @@
|
|||
//using Microsoft.EntityFrameworkCore;
|
||||
//using Microsoft.EntityFrameworkCore.Storage;
|
||||
//using ShardingCore.Sharding.Abstractions;
|
||||
//using System;
|
||||
//using System.Collections.Concurrent;
|
||||
//using System.Data;
|
||||
//using System.Threading;
|
||||
//using System.Threading.Tasks;
|
||||
|
||||
//namespace ShardingCore.Sharding.ShardingTransactions
|
||||
//{
|
||||
// /*
|
||||
// * @Author: xjm
|
||||
// * @Description:
|
||||
// * @Date: 2021/9/18 13:02:32
|
||||
// * @Ver: 1.0
|
||||
// * @Email: 326308290@qq.com
|
||||
// */
|
||||
// public class ShardingTransaction : IShardingTransaction
|
||||
// {
|
||||
// private readonly IShardingDbContextExecutor _shardingDbContextExecutor;
|
||||
|
||||
// private readonly ConcurrentDictionary<string, IDbContextTransaction> _dbContextTransactions =
|
||||
// new ConcurrentDictionary<string, IDbContextTransaction>();
|
||||
|
||||
// private IsolationLevel isolationLevel = IsolationLevel.Unspecified;
|
||||
|
||||
// private bool _isBeginTransaction = false;
|
||||
// /// <summary>
|
||||
// /// 是否需要抛出异常
|
||||
// /// </summary>
|
||||
// private bool _throwException => _dbContextTransactions.Count == 1;
|
||||
|
||||
// public ShardingTransaction(IShardingDbContextExecutor shardingDbContextExecutor)
|
||||
// {
|
||||
// _shardingDbContextExecutor = shardingDbContextExecutor;
|
||||
// }
|
||||
|
||||
// public bool IsBeginTransaction()
|
||||
// {
|
||||
// return _isBeginTransaction;
|
||||
// }
|
||||
|
||||
// public void BeginTransaction(IsolationLevel isolationLevel)
|
||||
// {
|
||||
// if (_isBeginTransaction)
|
||||
// throw new InvalidOperationException("transaction is already begin");
|
||||
// _isBeginTransaction = true;
|
||||
// this.isolationLevel = isolationLevel;
|
||||
|
||||
// }
|
||||
|
||||
|
||||
|
||||
// public void Use(string dataSourceName, DbContext dbContext)
|
||||
// {
|
||||
// if (!_isBeginTransaction)
|
||||
// throw new InvalidOperationException("transaction is not begin");
|
||||
// if (!_dbContextTransactions.TryGetValue(dataSourceName, out var dbContextTransaction))
|
||||
// {
|
||||
// dbContextTransaction = dbContext.Database.BeginTransaction(isolationLevel);
|
||||
// var tryAdd = _dbContextTransactions.TryAdd(dataSourceName, dbContextTransaction);
|
||||
// if (!tryAdd)
|
||||
// throw new InvalidOperationException("append transaction error");
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// dbContext.Database.NotifyTransaction(dbContextTransaction.GetDbTransaction());
|
||||
// }
|
||||
// }
|
||||
|
||||
// public void Rollback()
|
||||
// {
|
||||
// foreach (var dbContextTransaction in _dbContextTransactions)
|
||||
// {
|
||||
// try
|
||||
// {
|
||||
// dbContextTransaction.Value.Rollback();
|
||||
// }
|
||||
// catch (Exception e)
|
||||
// {
|
||||
// Console.WriteLine($"rollback error:[{e}]");
|
||||
// if (_throwException)
|
||||
// throw;
|
||||
// }
|
||||
// }
|
||||
// this._shardingDbContextExecutor.ClearTransaction();
|
||||
// }
|
||||
|
||||
// public void Commit()
|
||||
// {
|
||||
// foreach (var dbContextTransaction in _dbContextTransactions)
|
||||
// {
|
||||
// try
|
||||
// {
|
||||
// dbContextTransaction.Value.Commit();
|
||||
// }
|
||||
// catch (Exception e)
|
||||
// {
|
||||
// Console.WriteLine($"commit error:[{e}]");
|
||||
// if (_throwException)
|
||||
// throw;
|
||||
// }
|
||||
// }
|
||||
// this._shardingDbContextExecutor.ClearTransaction();
|
||||
// }
|
||||
|
||||
//#if !EFCORE2
|
||||
|
||||
// public async Task RollbackAsync(CancellationToken cancellationToken = new CancellationToken())
|
||||
// {
|
||||
// foreach (var dbContextTransaction in _dbContextTransactions)
|
||||
// {
|
||||
// try
|
||||
// {
|
||||
// await dbContextTransaction.Value.RollbackAsync(cancellationToken);
|
||||
// }
|
||||
// catch (Exception e)
|
||||
// {
|
||||
// Console.WriteLine($"rollback error:[{e}]");
|
||||
// if (_throwException)
|
||||
// throw;
|
||||
// }
|
||||
// }
|
||||
// await this._shardingDbContextExecutor.ClearTransactionAsync(cancellationToken);
|
||||
// }
|
||||
// public async Task CommitAsync(CancellationToken cancellationToken = new CancellationToken())
|
||||
// {
|
||||
// foreach (var dbContextTransaction in _dbContextTransactions)
|
||||
// {
|
||||
// try
|
||||
// {
|
||||
// await dbContextTransaction.Value.CommitAsync(cancellationToken);
|
||||
// }
|
||||
// catch (Exception e)
|
||||
// {
|
||||
// Console.WriteLine($"commit error:[{e}]");
|
||||
// if (_throwException)
|
||||
// throw;
|
||||
// }
|
||||
// }
|
||||
// await this._shardingDbContextExecutor.ClearTransactionAsync(cancellationToken);
|
||||
// }
|
||||
// public async ValueTask DisposeAsync()
|
||||
// {
|
||||
// foreach (var dbContextTransaction in _dbContextTransactions)
|
||||
// {
|
||||
// try
|
||||
// {
|
||||
// await dbContextTransaction.Value.DisposeAsync();
|
||||
// }
|
||||
// catch (Exception e)
|
||||
// {
|
||||
// Console.WriteLine($"dispose error:[{e}]");
|
||||
// }
|
||||
// }
|
||||
// _dbContextTransactions.Clear();
|
||||
// }
|
||||
//#endif
|
||||
|
||||
// public void Dispose()
|
||||
// {
|
||||
|
||||
// foreach (var dbContextTransaction in _dbContextTransactions)
|
||||
// {
|
||||
// try
|
||||
// {
|
||||
// dbContextTransaction.Value.Dispose();
|
||||
// }
|
||||
// catch (Exception e)
|
||||
// {
|
||||
// Console.WriteLine($"dispose error:[{e}]");
|
||||
// }
|
||||
// }
|
||||
// _dbContextTransactions.Clear();
|
||||
// }
|
||||
|
||||
// }
|
||||
//}
|
Loading…
Reference in New Issue