优化全构造函数的group by对象处理

This commit is contained in:
xuejiaming 2023-01-03 17:16:45 +08:00
parent 14b0f747fb
commit fd548bd258
10 changed files with 113 additions and 84 deletions

View File

@ -255,5 +255,16 @@ namespace Sample.MySql.Controllers
// var sysUserMods2 = await _defaultTableDbContext.Set<SysTest>().FromSqlRaw("select * from SysTest where id='2'").ToListAsync(); // var sysUserMods2 = await _defaultTableDbContext.Set<SysTest>().FromSqlRaw("select * from SysTest where id='2'").ToListAsync();
return Ok(); return Ok();
} }
[HttpGet]
public async Task<IActionResult> Get7()
{
var sysUserMod = await _defaultTableDbContext.Set<SysUserMod>().FindAsync("101");
sysUserMod.Age = new Random().Next(1,999);
_defaultTableDbContext.Update(sysUserMod);
_defaultTableDbContext.SaveChanges();
// var sysUserMods1 = await _defaultTableDbContext.Set<SysUserMod>().FromSqlRaw("select * from SysUserMod where id='2'").ToListAsync();
// var sysUserMods2 = await _defaultTableDbContext.Set<SysTest>().FromSqlRaw("select * from SysTest where id='2'").ToListAsync();
return Ok();
}
} }
} }

View File

@ -43,7 +43,7 @@ namespace Sample.MySql.DbContexts
// modelBuilder.Entity<SysUserLogByMonth>().HasData(new SysUserLogByMonth() { Id = "1", Time = DateTime.Now }); // modelBuilder.Entity<SysUserLogByMonth>().HasData(new SysUserLogByMonth() { Id = "1", Time = DateTime.Now });
// modelBuilder.Entity<SysTest>().HasData(new SysTest() { Id = "1", UserId = "123" }); // modelBuilder.Entity<SysTest>().HasData(new SysTest() { Id = "1", UserId = "123" });
// modelBuilder.Entity<TestMod>().ToTable(nameof(TestMod)); // modelBuilder.Entity<TestMod>().ToTable(nameof(TestMod));
// modelBuilder.Entity<TestModItem>().ToTable(nameof(TestModItem)); // modelBuilder.Entity<SysTest>().ToTable("xxx");
} }

View File

@ -26,36 +26,36 @@ namespace Samples.AbpSharding
public abstract class AbstractShardingAbpDbContext<TDbContext> : AbpDbContext<TDbContext>, IShardingDbContext public abstract class AbstractShardingAbpDbContext<TDbContext> : AbpDbContext<TDbContext>, IShardingDbContext
where TDbContext : DbContext where TDbContext : DbContext
{ {
private readonly IShardingDbContextExecutor _shardingDbContextExecutor;
protected AbstractShardingAbpDbContext(DbContextOptions<TDbContext> options) : base(options) protected AbstractShardingAbpDbContext(DbContextOptions<TDbContext> options) : base(options)
{ {
}
var wrapOptionsExtension = options.FindExtension<ShardingWrapOptionsExtension>();
if (wrapOptionsExtension != null) private IShardingDbContextExecutor _shardingDbContextExecutor;
public IShardingDbContextExecutor GetShardingExecutor()
{ {
_shardingDbContextExecutor = new ShardingDbContextExecutor(this); return _shardingDbContextExecutor??=DoCreateShardingDbContextExecutor();
_shardingDbContextExecutor.EntityCreateDbContextBefore += (sender, args) => }
private IShardingDbContextExecutor DoCreateShardingDbContextExecutor()
{
var shardingDbContextExecutor = this.CreateShardingDbContextExecutor()!;
shardingDbContextExecutor.EntityCreateDbContextBefore += (sender, args) =>
{ {
CheckAndSetShardingKeyThatSupportAutoCreate(args.Entity); CheckAndSetShardingKeyThatSupportAutoCreate(args.Entity);
}; };
_shardingDbContextExecutor.CreateDbContextAfter += (sender, args) => shardingDbContextExecutor.CreateDbContextAfter += (sender, args) =>
{ {
var shardingDbContextExecutor = (IShardingDbContextExecutor)sender;
var argsDbContext = args.DbContext; var argsDbContext = args.DbContext;
var shellDbContext = shardingDbContextExecutor.GetShellDbContext();
if (argsDbContext is AbpDbContext<TDbContext> abpDbContext&&shellDbContext is AbpDbContext<TDbContext> abpShellDbContext && if (argsDbContext is AbpDbContext<TDbContext> abpDbContext&&
abpDbContext.LazyServiceProvider == null) abpDbContext.LazyServiceProvider == null)
{ {
abpDbContext.LazyServiceProvider = abpShellDbContext.LazyServiceProvider; abpDbContext.LazyServiceProvider = this.LazyServiceProvider;
} }
}; };
} return shardingDbContextExecutor;
}
public IShardingDbContextExecutor GetShardingExecutor()
{
return _shardingDbContextExecutor;
} }

View File

@ -34,36 +34,35 @@ namespace Samples.AbpSharding
where TUser : AbpUser<TUser> where TUser : AbpUser<TUser>
where TSelf : AbpZeroDbContext<TTenant, TRole, TUser, TSelf> where TSelf : AbpZeroDbContext<TTenant, TRole, TUser, TSelf>
{ {
private readonly IShardingDbContextExecutor _shardingDbContextExecutor;
protected AbstractShardingAbpZeroDbContext(DbContextOptions<TSelf> options) protected AbstractShardingAbpZeroDbContext(DbContextOptions<TSelf> options)
: base(options) : base(options)
{ {
var wrapOptionsExtension = options.FindExtension<ShardingWrapOptionsExtension>();
if (wrapOptionsExtension != null)
{
_shardingDbContextExecutor = new ShardingDbContextExecutor(this);
_shardingDbContextExecutor.EntityCreateDbContextBefore += (sender, args) =>
{
CheckAndSetShardingKeyThatSupportAutoCreate(args.Entity);
};
_shardingDbContextExecutor.CreateDbContextAfter += (sender, args) =>
{
var shardingDbContextExecutor = (IShardingDbContextExecutor)sender;
var argsDbContext = args.DbContext;
var shellDbContext = shardingDbContextExecutor.GetShellDbContext();
FillDbContextInject(shellDbContext, argsDbContext);
};
}
} }
public IRouteTail RouteTail { get; set; } public IRouteTail RouteTail { get; set; }
#region Sharding Core #region Sharding Core
private IShardingDbContextExecutor _shardingDbContextExecutor;
public IShardingDbContextExecutor GetShardingExecutor() public IShardingDbContextExecutor GetShardingExecutor()
{ {
return _shardingDbContextExecutor; return _shardingDbContextExecutor??=DoCreateShardingDbContextExecutor();
}
private IShardingDbContextExecutor DoCreateShardingDbContextExecutor()
{
var shardingDbContextExecutor = this.CreateShardingDbContextExecutor()!;
shardingDbContextExecutor.EntityCreateDbContextBefore += (sender, args) =>
{
CheckAndSetShardingKeyThatSupportAutoCreate(args.Entity);
};
shardingDbContextExecutor.CreateDbContextAfter += (sender, args) =>
{
var argsDbContext = args.DbContext;
FillDbContextInject(argsDbContext);
};
return shardingDbContextExecutor;
} }
#endregion #endregion
@ -117,48 +116,47 @@ namespace Samples.AbpSharding
/// <summary> /// <summary>
/// 填充DbContext需要的依赖项 /// 填充DbContext需要的依赖项
/// </summary> /// </summary>
/// <param name="shellDbContext"></param>
/// <param name="dbContext"></param> /// <param name="dbContext"></param>
protected virtual void FillDbContextInject(DbContext shellDbContext,DbContext dbContext) protected virtual void FillDbContextInject(DbContext dbContext)
{ {
if (shellDbContext is AbpZeroCommonDbContext<TRole, TUser, TSelf> abpShellDbContext&& dbContext is AbpZeroCommonDbContext<TRole, TUser, TSelf> abpDbContext) if ( dbContext is AbpZeroCommonDbContext<TRole, TUser, TSelf> abpDbContext)
{ {
// AbpZeroCommonDbContext // AbpZeroCommonDbContext
if (abpDbContext.EntityHistoryHelper == null) if (abpDbContext.EntityHistoryHelper == null)
{ {
abpDbContext.EntityHistoryHelper = abpShellDbContext.EntityHistoryHelper; abpDbContext.EntityHistoryHelper = this.EntityHistoryHelper;
} }
// AbpDbContext // AbpDbContext
if (abpDbContext.AbpSession == null) if (abpDbContext.AbpSession == null)
{ {
abpDbContext.AbpSession = abpShellDbContext.AbpSession; abpDbContext.AbpSession = this.AbpSession;
} }
if (abpDbContext.EntityChangeEventHelper == null) if (abpDbContext.EntityChangeEventHelper == null)
{ {
abpDbContext.EntityChangeEventHelper = abpShellDbContext.EntityChangeEventHelper; abpDbContext.EntityChangeEventHelper = this.EntityChangeEventHelper;
} }
if (abpDbContext.Logger == null) if (abpDbContext.Logger == null)
{ {
abpDbContext.Logger = abpShellDbContext.Logger; abpDbContext.Logger = this.Logger;
} }
if (abpDbContext.EventBus == null) if (abpDbContext.EventBus == null)
{ {
abpDbContext.EventBus = abpShellDbContext.EventBus; abpDbContext.EventBus = this.EventBus;
} }
if (abpDbContext.GuidGenerator == null) if (abpDbContext.GuidGenerator == null)
{ {
abpDbContext.GuidGenerator = abpShellDbContext.GuidGenerator; abpDbContext.GuidGenerator = this.GuidGenerator;
} }
if (abpDbContext.CurrentUnitOfWorkProvider == null) if (abpDbContext.CurrentUnitOfWorkProvider == null)
{ {
abpDbContext.CurrentUnitOfWorkProvider = abpShellDbContext.CurrentUnitOfWorkProvider; abpDbContext.CurrentUnitOfWorkProvider = this.CurrentUnitOfWorkProvider;
} }
if (abpDbContext.MultiTenancyConfig == null) if (abpDbContext.MultiTenancyConfig == null)
{ {
abpDbContext.MultiTenancyConfig = abpShellDbContext.MultiTenancyConfig; abpDbContext.MultiTenancyConfig = this.MultiTenancyConfig;
} }
abpDbContext.SuppressAutoSetTenantId = abpShellDbContext.SuppressAutoSetTenantId; abpDbContext.SuppressAutoSetTenantId = this.SuppressAutoSetTenantId;
} }
} }

View File

@ -2,9 +2,12 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using ShardingCore.Core.RuntimeContexts; using ShardingCore.Core.RuntimeContexts;
using ShardingCore.Sharding.Abstractions;
using ShardingCore.Sharding.ShardingDbContextExecutors;
namespace ShardingCore.EFCores namespace ShardingCore.EFCores
{ {

View File

@ -14,11 +14,24 @@ using ShardingCore.Core.VirtualRoutes.TableRoutes.RouteTails.Abstractions;
using ShardingCore.EFCores; using ShardingCore.EFCores;
using ShardingCore.Sharding; using ShardingCore.Sharding;
using ShardingCore.Sharding.Abstractions; using ShardingCore.Sharding.Abstractions;
using ShardingCore.Sharding.ShardingDbContextExecutors;
namespace ShardingCore.Extensions namespace ShardingCore.Extensions
{ {
public static class ShardingDbContextExtension public static class ShardingDbContextExtension
{ {
public static IShardingDbContextExecutor? CreateShardingDbContextExecutor<TDbContext>(
this TDbContext shellDbContext)
where TDbContext:DbContext,IShardingDbContext
{
var shardingWrapOptionsExtension = shellDbContext.GetService<IDbContextOptions>().FindExtension<ShardingWrapOptionsExtension>();
if (shardingWrapOptionsExtension != null)
{
return new ShardingDbContextExecutor(shellDbContext);
}
return default;
}
public static bool IsUseReadWriteSeparation(this IShardingDbContext shardingDbContext) public static bool IsUseReadWriteSeparation(this IShardingDbContext shardingDbContext)
{ {
return shardingDbContext.GetShardingExecutor().GetVirtualDataSource().UseReadWriteSeparation; return shardingDbContext.GetShardingExecutor().GetVirtualDataSource().UseReadWriteSeparation;

View File

@ -7,7 +7,9 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Infrastructure;
using ShardingCore.EFCores; using ShardingCore.EFCores;
using ShardingCore.Extensions;
namespace ShardingCore.Sharding namespace ShardingCore.Sharding
{ {
@ -23,35 +25,33 @@ namespace ShardingCore.Sharding
/// </summary> /// </summary>
public abstract class AbstractShardingDbContext : DbContext, IShardingDbContext public abstract class AbstractShardingDbContext : DbContext, IShardingDbContext
{ {
protected IShardingDbContextExecutor ShardingDbContextExecutor { get; } /// <summary>
/// 构造函数
/// </summary>
public AbstractShardingDbContext(DbContextOptions options) : base(options) /// <param name="options"></param>
protected AbstractShardingDbContext(DbContextOptions options) : base(options)
{ {
var wrapOptionsExtension = options.FindExtension<ShardingWrapOptionsExtension>();
if (wrapOptionsExtension != null)
{
ShardingDbContextExecutor = new ShardingDbContextExecutor(this);
}
} }
private IShardingDbContextExecutor _shardingDbContextExecutor;
public IShardingDbContextExecutor GetShardingExecutor() public IShardingDbContextExecutor GetShardingExecutor()
{ {
return ShardingDbContextExecutor; return _shardingDbContextExecutor??=this.CreateShardingDbContextExecutor();
} }
public override void Dispose() public override void Dispose()
{ {
ShardingDbContextExecutor?.Dispose(); _shardingDbContextExecutor?.Dispose();
base.Dispose(); base.Dispose();
} }
#if !EFCORE2 #if !EFCORE2
public override async ValueTask DisposeAsync() public override async ValueTask DisposeAsync()
{ {
if (ShardingDbContextExecutor!=null) if (_shardingDbContextExecutor!=null)
{ {
await ShardingDbContextExecutor.DisposeAsync(); await _shardingDbContextExecutor.DisposeAsync();
} }
await base.DisposeAsync(); await base.DisposeAsync();

View File

@ -37,10 +37,10 @@ namespace ShardingCore.Sharding.Enumerators.AggregateExtensions
} }
else else
{ {
var parameters = allProperties.Select(o => o.GetValue(source)).ToArray();
if (anonType.GetConstructors().Length == 1 && if (anonType.GetConstructors().Length == 1 &&
anonType.GetConstructors()[0].GetParameters().Length == allPropertyTypes.Length) anonType.GetConstructors()[0].GetParameters().Length == allPropertyTypes.Length)
{ {
var parameters = allProperties.Select(o => o.GetValue(source)).ToArray();
return (TSource)Activator.CreateInstance(anonType, parameters); return (TSource)Activator.CreateInstance(anonType, parameters);
} }
else else

View File

@ -123,12 +123,11 @@ namespace ShardingCore
shardingConfigOptions.ShardingMigrationConfigure?.Invoke(dbContextOptionsBuilder); shardingConfigOptions.ShardingMigrationConfigure?.Invoke(dbContextOptionsBuilder);
var virtualDataSource = shardingRuntimeContext.GetVirtualDataSource(); var virtualDataSource = shardingRuntimeContext.GetVirtualDataSource();
var connectionString = virtualDataSource.GetConnectionString(virtualDataSource.DefaultDataSourceName); var connectionString = virtualDataSource.GetConnectionString(virtualDataSource.DefaultDataSourceName);
var contextOptionsBuilder = virtualDataSource.ConfigurationParams virtualDataSource.ConfigurationParams
.UseDbContextOptionsBuilder(connectionString, dbContextOptionsBuilder) .UseDbContextOptionsBuilder(connectionString, dbContextOptionsBuilder)
.UseShardingMigrator()
.UseSharding(shardingRuntimeContext); .UseSharding(shardingRuntimeContext);
virtualDataSource.ConfigurationParams.UseShellDbContextOptionBuilder(contextOptionsBuilder); virtualDataSource.ConfigurationParams.UseShellDbContextOptionBuilder(dbContextOptionsBuilder);
return dbContextOptionsBuilder; return dbContextOptionsBuilder;
} }
@ -210,20 +209,27 @@ namespace ShardingCore
return services; return services;
} }
#pragma warning disable EF1001
/// <summary>
///
/// </summary>
/// <param name="optionsBuilder"></param>
/// <param name="shardingRuntimeContext"></param>
/// <returns></returns>
public static DbContextOptionsBuilder UseSharding( public static DbContextOptionsBuilder UseSharding(
this DbContextOptionsBuilder optionsBuilder, IShardingRuntimeContext shardingRuntimeContext) this DbContextOptionsBuilder optionsBuilder, IShardingRuntimeContext shardingRuntimeContext)
{ {
return optionsBuilder.UseShardingWrapMark().UseShardingOptions(shardingRuntimeContext) return optionsBuilder
// .ReplaceService<IDbSetSource, ShardingDbSetSource>() .UseShardingWrapMark()
.UseShardingMigrator()
.UseShardingOptions(shardingRuntimeContext)
.ReplaceService<IQueryCompiler, ShardingQueryCompiler>() .ReplaceService<IQueryCompiler, ShardingQueryCompiler>()
.ReplaceService<IChangeTrackerFactory, ShardingChangeTrackerFactory>() .ReplaceService<IChangeTrackerFactory, ShardingChangeTrackerFactory>()
.ReplaceService<IDbContextTransactionManager, .ReplaceService<IDbContextTransactionManager,ShardingRelationalTransactionManager>()
ShardingRelationalTransactionManager>() .ReplaceService<IStateManager,ShardingStateManager>()
.ReplaceService<IStateManager, .ReplaceService<IRelationalTransactionFactory,ShardingRelationalTransactionFactory>();
ShardingStateManager>()
.ReplaceService<IRelationalTransactionFactory,
ShardingRelationalTransactionFactory>();
} }
#pragma warning restore EF1001
public static DbContextOptionsBuilder UseShardingMigrator( public static DbContextOptionsBuilder UseShardingMigrator(
this DbContextOptionsBuilder optionsBuilder) this DbContextOptionsBuilder optionsBuilder)
@ -248,12 +254,10 @@ namespace ShardingCore
((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(shardingWrapExtension); ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(shardingWrapExtension);
return optionsBuilder; return optionsBuilder;
} }
private static ShardingWrapOptionsExtension CreateOrGetShardingWrapExtension( private static ShardingWrapOptionsExtension CreateOrGetShardingWrapExtension(
this DbContextOptionsBuilder optionsBuilder) this DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.Options.FindExtension<ShardingWrapOptionsExtension>() ?? => optionsBuilder.Options.FindExtension<ShardingWrapOptionsExtension>() ??
new ShardingWrapOptionsExtension(); new ShardingWrapOptionsExtension();
private static ShardingOptionsExtension CreateOrGetShardingOptionsExtension( private static ShardingOptionsExtension CreateOrGetShardingOptionsExtension(
this DbContextOptionsBuilder optionsBuilder, IShardingRuntimeContext shardingRuntimeContext) => this DbContextOptionsBuilder optionsBuilder, IShardingRuntimeContext shardingRuntimeContext) =>
optionsBuilder.Options.FindExtension<ShardingOptionsExtension>() ?? optionsBuilder.Options.FindExtension<ShardingOptionsExtension>() ??