dotnetcore / sharding-core

high performance lightweight solution for efcore sharding table and sharding database support read-write-separation .一款ef-core下高性能、轻量级针对分表分库读写分离的解决方案,具有零依赖、零学习成本、零业务代码入侵
https://xuejmnet.github.io/sharding-core-doc/
Apache License 2.0
1.17k stars 171 forks source link

sharding-core-7.x.1.17 调用DbContext.SaveChanges(), 不能保存自动追踪实体的修改, 报DbUpdateConcurrencyException错误. #259

Closed wanghucheng66 closed 1 year ago

wanghucheng66 commented 1 year ago

我的分片表使用了按年份分表 AbstractSimpleShardingYearKeyDateTimeVirtualTableRoute 没有进行分库, 只有一个数据库. Sharding-core版本 sharding-core-7.x.1.17 .NET版本 .Net6.0.23 EFCore版本: Microsoft.EntityFrameworkCore.7.0.13 数据库: MS SQL Server 2017

修改字段代码: 数据可以正常查询出来, 但是无论数据处于那个年份的分片表中, 保存更改的时候都会报错. 从日志看, 保存的时候输出的SQL更新语句都是 UPDATE [dbo].[DistributorInventoryDaily]. 没有更新到正确的表.

 [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            var entity = db.Set<DistributorInventoryDaily>().Where(a => a.ID == 47252775).First();

            entity.Creator = "Sharding";
            var rows = db.SaveChanges();

            Console.WriteLine($"Changed {rows}");
            return Ok();
      }

分表路由:

public class DistributorInventoryDailyVirtualTableRoute : AbstractSimpleShardingYearKeyDateTimeVirtualTableRoute<DistributorInventoryDaily>
    {
        private readonly string _TableSeparator = string.Empty;
        private readonly DateTime _BeginTime = new DateTime(2018, 1, 1);

        private static readonly string _EmptyTail = string.Empty;
        private static readonly EmptyMaxComparer _emptyMaxComparer = new EmptyMaxComparer();
        /// <summary>
        /// 切分日期, 返回3个月前的日期.
        /// </summary>
        private DateTime SplitDate
        {
            get
            {
                return DateTime.Today.AddDays(-93);
            }
        }

        /// <summary>
        ///  不使用程序自动建表, 使用存储过程建表.
        /// </summary>
        /// <returns></returns>
        public override bool AutoCreateTableByTime()
        {
            return false;
        }

        public override void Configure(EntityMetadataTableBuilder<DistributorInventoryDaily> builder)
        {
            //使用空字符串进行分割, 可以在返回尾巴列表时增加一个空尾巴的表.
            builder.TableSeparator(_TableSeparator);
            builder.ShardingProperty(o => o.InventoryDate);
        }

        /// <summary>
        /// 分片开始时间
        /// </summary>
        /// <returns></returns>
        public override DateTime GetBeginTime()
        {
            return _BeginTime;
        }

        /// <summary>
        /// 返回null表示不开启
        /// </summary>
        /// <returns></returns>
        public override IPaginationConfiguration<DistributorInventoryDaily> CreatePaginationConfiguration()
        {
            return new DistributorInventoryDailyPaginationConfiguration();
        }

        protected override List<string> CalcTailsOnStart()
        {
            var tails = base.CalcTailsOnStart();
            if (!tails.Contains(_EmptyTail))
            {
                tails.Add(_EmptyTail);
            }
            return tails;
        }

        /// <summary>
        /// 返回的尾巴中增加一个空尾巴
        /// </summary>
        /// <returns></returns>
        public override List<string> GetTails()
        {
            var tails = base.GetTails();
            return tails;
        }

        /// <summary>
        /// 比较EmptyTail和其他Tail的大小.
        /// </summary>
        /// <param name="shardingKey"></param>
        /// <param name="shardingOperator"></param>
        /// <returns></returns>
        public override Func<string, bool> GetRouteToFilter(DateTime shardingKey, ShardingOperatorEnum shardingOperator)
        {
            var shardingTail = ShardingKeyToTail(shardingKey);
            switch (shardingOperator)
            {
                case ShardingOperatorEnum.GreaterThan:
                    return tail => _emptyMaxComparer.Compare(tail, shardingTail) >= 0;
                case ShardingOperatorEnum.GreaterThanOrEqual:
                    return tail => _emptyMaxComparer.Compare(tail, shardingTail) >= 0;
                case ShardingOperatorEnum.LessThan:
                    return tail => _emptyMaxComparer.Compare(tail, shardingTail) <= 0;
                case ShardingOperatorEnum.LessThanOrEqual:
                    return tail => _emptyMaxComparer.Compare(tail, shardingTail) <= 0;
                case ShardingOperatorEnum.Equal: return tail => tail == shardingTail;
                default:
                {
#if DEBUG
                    Console.WriteLine($"shardingOperator is not equal scan all table tail");
#endif
                    return tail => true;
                }
                //return base.GetRouteToFilter(shardingKey, shardingOperator);
            }
        }

        /// <summary>
        /// How convert sharding key to tail
        /// </summary>
        /// <param name="shardingKey"></param>
        /// <returns></returns>
        public override string ShardingKeyToTail(object shardingKey)
        {
            var dateTime = Convert.ToDateTime(shardingKey);
            if (dateTime >= SplitDate)
            {
                return _EmptyTail;
            }
            return base.ShardingKeyToTail(shardingKey);
        }

        /// <summary>
        /// How convert time to tail
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        protected override string TimeFormatToTail(DateTime time)
        {
            if (time >= SplitDate)
            {
                return _EmptyTail;
            }
            return base.TimeFormatToTail(time);
        }

        /// <summary>
        /// 分页配置.
        /// </summary>
        public class DistributorInventoryDailyPaginationConfiguration : IPaginationConfiguration<DistributorInventoryDaily>
        {
            public void Configure(PaginationBuilder<DistributorInventoryDaily> builder)
            {
                builder.PaginationSequence(o => o.InventoryDate)
                    .UseRouteComparerAsc(_emptyMaxComparer)
                    .UseQueryMatch(PaginationMatchEnum.Owner | PaginationMatchEnum.Named | PaginationMatchEnum.PrimaryMatch)
                    .UseAppendIfOrderNone();
                //启用反向排序,当分页total大于10000以上且本次查询skip的数目超过总的total的1 / 2那么就会启用反向排序
                builder.ConfigReverseShardingPage(0.5d, 10000L);
            }
        }

        /// <summary>
        /// 后缀比较器
        /// </summary>
        public class EmptyMaxComparer : IComparer<string>
        {
            public int Compare(string? x, string? y)
            {
                if (!Object.Equals(x, y))
                {
                    if (_EmptyTail.Equals(x))
                        return 1;
                    if (_EmptyTail.Equals(y))
                        return -1;
                }
                return Comparer<string>.Default.Compare(x, y);
            }
        }
    }

报错详细信息

14:29:57:949    'EfCoreWebApp.exe' (CoreCLR: clrhost): Loaded 'C:\Repositories\ShardingDemo\shardingCore7.17\EfCoreWebApp\bin\Debug\net6.0\Microsoft.SqlServer.Server.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
14:29:57:949    Microsoft.EntityFrameworkCore.Database.Command: Information: Executed DbCommand (202ms) [Parameters=[@__p_0='?' (DbType = Int32)], CommandType='Text', CommandTimeout='120']
14:29:57:949    SELECT TOP(@__p_0) [d].[ID], [d].[BatchNumberID], [d].[CreateTime], [d].[Creator], [d].[DistributorID], [d].[EnumEntityStatus], [d].[FinalEditTime], [d].[FinalEditor], [d].[InventoryDate], [d].[IsDefaultProductBatch], [d].[IsExpire], [d].[IsLatest], [d].[IsUnauthorizedProduct], [d].[MaterialGroupID], [d].[MaterialID], [d].[ProductID], [d].[Quantity], [d].[QueryCode], [d].[SalesFlowCycleID], [d].[SalesFlowSourceID], [d].[TierID]
14:29:57:949    FROM [dbo].[DistributorInventoryDaily2018] AS [d]
14:29:57:949    WHERE [d].[ID] = 47252775
14:29:58:189    Microsoft.EntityFrameworkCore.Database.Command: Information: Executed DbCommand (80ms) [Parameters=[@__p_0='?' (DbType = Int32)], CommandType='Text', CommandTimeout='120']
14:29:58:189    SELECT TOP(@__p_0) [d].[ID], [d].[BatchNumberID], [d].[CreateTime], [d].[Creator], [d].[DistributorID], [d].[EnumEntityStatus], [d].[FinalEditTime], [d].[FinalEditor], [d].[InventoryDate], [d].[IsDefaultProductBatch], [d].[IsExpire], [d].[IsLatest], [d].[IsUnauthorizedProduct], [d].[MaterialGroupID], [d].[MaterialID], [d].[ProductID], [d].[Quantity], [d].[QueryCode], [d].[SalesFlowCycleID], [d].[SalesFlowSourceID], [d].[TierID]
14:29:58:189    FROM [dbo].[DistributorInventoryDaily2019] AS [d]
14:29:58:189    WHERE [d].[ID] = 47252775
14:29:58:512    Microsoft.EntityFrameworkCore.Database.Command: Information: Executed DbCommand (80ms) [Parameters=[@__p_0='?' (DbType = Int32)], CommandType='Text', CommandTimeout='120']
14:29:58:512    SELECT TOP(@__p_0) [d].[ID], [d].[BatchNumberID], [d].[CreateTime], [d].[Creator], [d].[DistributorID], [d].[EnumEntityStatus], [d].[FinalEditTime], [d].[FinalEditor], [d].[InventoryDate], [d].[IsDefaultProductBatch], [d].[IsExpire], [d].[IsLatest], [d].[IsUnauthorizedProduct], [d].[MaterialGroupID], [d].[MaterialID], [d].[ProductID], [d].[Quantity], [d].[QueryCode], [d].[SalesFlowCycleID], [d].[SalesFlowSourceID], [d].[TierID]
14:29:58:512    FROM [dbo].[DistributorInventoryDaily2020] AS [d]
14:29:58:512    WHERE [d].[ID] = 47252775
14:29:58:512    Microsoft.EntityFrameworkCore.Database.Command: Information: Executed DbCommand (81ms) [Parameters=[@__p_0='?' (DbType = Int32)], CommandType='Text', CommandTimeout='120']
14:29:58:512    SELECT TOP(@__p_0) [d].[ID], [d].[BatchNumberID], [d].[CreateTime], [d].[Creator], [d].[DistributorID], [d].[EnumEntityStatus], [d].[FinalEditTime], [d].[FinalEditor], [d].[InventoryDate], [d].[IsDefaultProductBatch], [d].[IsExpire], [d].[IsLatest], [d].[IsUnauthorizedProduct], [d].[MaterialGroupID], [d].[MaterialID], [d].[ProductID], [d].[Quantity], [d].[QueryCode], [d].[SalesFlowCycleID], [d].[SalesFlowSourceID], [d].[TierID]
14:29:58:512    FROM [dbo].[DistributorInventoryDaily2021] AS [d]
14:29:58:512    WHERE [d].[ID] = 47252775
14:29:58:689    Microsoft.EntityFrameworkCore.Database.Command: Information: Executed DbCommand (78ms) [Parameters=[@__p_0='?' (DbType = Int32)], CommandType='Text', CommandTimeout='120']
14:29:58:689    SELECT TOP(@__p_0) [d].[ID], [d].[BatchNumberID], [d].[CreateTime], [d].[Creator], [d].[DistributorID], [d].[EnumEntityStatus], [d].[FinalEditTime], [d].[FinalEditor], [d].[InventoryDate], [d].[IsDefaultProductBatch], [d].[IsExpire], [d].[IsLatest], [d].[IsUnauthorizedProduct], [d].[MaterialGroupID], [d].[MaterialID], [d].[ProductID], [d].[Quantity], [d].[QueryCode], [d].[SalesFlowCycleID], [d].[SalesFlowSourceID], [d].[TierID]
14:29:58:689    FROM [dbo].[DistributorInventoryDaily2022] AS [d]
14:29:58:689    WHERE [d].[ID] = 47252775
14:29:58:689    Microsoft.EntityFrameworkCore.Database.Command: Information: Executed DbCommand (77ms) [Parameters=[@__p_0='?' (DbType = Int32)], CommandType='Text', CommandTimeout='120']
14:29:58:689    SELECT TOP(@__p_0) [d].[ID], [d].[BatchNumberID], [d].[CreateTime], [d].[Creator], [d].[DistributorID], [d].[EnumEntityStatus], [d].[FinalEditTime], [d].[FinalEditor], [d].[InventoryDate], [d].[IsDefaultProductBatch], [d].[IsExpire], [d].[IsLatest], [d].[IsUnauthorizedProduct], [d].[MaterialGroupID], [d].[MaterialID], [d].[ProductID], [d].[Quantity], [d].[QueryCode], [d].[SalesFlowCycleID], [d].[SalesFlowSourceID], [d].[TierID]
14:29:58:689    FROM [dbo].[DistributorInventoryDaily2023] AS [d]
14:29:58:689    WHERE [d].[ID] = 47252775
14:30:01:944    'EfCoreWebApp.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\PrivateAssemblies\Runtime\Microsoft.VisualStudio.Debugger.Runtime.NetCoreApp.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
14:30:53:985    The thread 0x37d4 has exited with code 0 (0x0).
14:30:53:985    The thread 0x3a6c has exited with code 0 (0x0).
14:30:54:716    The thread 0x627c has exited with code 0 (0x0).
14:30:54:716    The thread 0x5ea8 has exited with code 0 (0x0).
14:30:54:716    The thread 0x534c has exited with code 0 (0x0).
14:30:54:716    The thread 0x78d8 has exited with code 0 (0x0).
14:30:58:219    Microsoft.EntityFrameworkCore.Database.Command: Information: Executed DbCommand (75ms) [Parameters=[@p1='?' (DbType = Int32), @p0='?' (Size = 4000)], CommandType='Text', CommandTimeout='120']
14:30:58:219    SET IMPLICIT_TRANSACTIONS OFF;
14:30:58:219    SET NOCOUNT ON;
14:30:58:219    UPDATE [dbo].[DistributorInventoryDaily] SET [Creator] = @p0
14:30:58:219    OUTPUT 1
14:30:58:219    WHERE [ID] = @p1;
14:30:58:460    Exception thrown: 'Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException' in Microsoft.EntityFrameworkCore.dll
14:30:58:460    An exception of type 'Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException' occurred in Microsoft.EntityFrameworkCore.dll but was not handled in user code
14:30:58:460    The database operation was expected to affect 1 row(s), but actually affected 0 row(s); data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.
14:30:58:460    
14:32:32:244    The thread 0x1bb4 has exited with code 0 (0x0).
14:32:32:244    The thread 0x80b0 has exited with code 0 (0x0).
14:32:32:244    The thread 0x8108 has exited with code 0 (0x0).
14:32:32:244    The thread 0x2b20 has exited with code 0 (0x0).
14:32:32:244    The thread 0x4fc0 has exited with code 0 (0x0).
14:32:34:988    Exception thrown: 'Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException' in Microsoft.EntityFrameworkCore.dll
14:32:34:988    An exception of type 'Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException' occurred in Microsoft.EntityFrameworkCore.dll but was not handled in user code
14:32:34:988    The database operation was expected to affect 1 row(s), but actually affected 0 row(s); data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.
14:32:34:988    
14:32:38:732    'EfCoreWebApp.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\6.0.23\System.Reflection.Metadata.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
14:32:38:732    Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware: Error: An unhandled exception has occurred while executing the request.
14:32:38:732    
14:32:38:732    Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: The database operation was expected to affect 1 row(s), but actually affected 0 row(s); data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.
14:32:38:732       at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ThrowAggregateUpdateConcurrencyException(RelationalDataReader reader, Int32 commandIndex, Int32 expectedRowsAffected, Int32 rowsAffected)
14:32:38:732       at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ConsumeResultSetWithRowsAffectedOnly(Int32 commandIndex, RelationalDataReader reader)
14:32:38:732       at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.Consume(RelationalDataReader reader)
14:32:38:732       at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
14:32:38:732       at Microsoft.EntityFrameworkCore.SqlServer.Update.Internal.SqlServerModificationCommandBatch.Execute(IRelationalConnection connection)
14:32:38:732       at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable`1 commandBatches, IRelationalConnection connection)
14:32:38:732       at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IList`1 entriesToSave)
14:32:38:732       at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(StateManager stateManager, Boolean acceptAllChangesOnSuccess)
14:32:38:732       at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
14:32:38:732       at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
14:32:38:732       at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
14:32:38:732       at ShardingCore.Sharding.ShardingDbContextExecutors.DataSourceDbContext.SaveChanges(Boolean acceptAllChangesOnSuccess) in C:\Repositories\ShardingDemo\shardingCore7.17\src\ShardingCore\Sharding\ShardingDbContextExecutors\DataSourceDbContext.cs:line 301
14:32:38:732       at ShardingCore.Sharding.ShardingDbContextExecutors.ShardingDbContextExecutor.SaveChanges(Boolean acceptAllChangesOnSuccess) in C:\Repositories\ShardingDemo\shardingCore7.17\src\ShardingCore\Sharding\ShardingDbContextExecutors\ShardingDbContextExecutor.cs:line 223
14:32:38:732       at ShardingCore.EFCores.ShardingStateManager.SaveChanges(Boolean acceptAllChangesOnSuccess) in C:\Repositories\ShardingDemo\shardingCore7.17\src\ShardingCore\EFCores\EFCore7x\ShardingStateManager.cs:line 77
14:32:38:732       at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
14:32:38:732       at EfCoreWebApp.Controllers.WeatherForecastController.Get() in C:\Repositories\ShardingDemo\shardingCore7.17\EfCoreWebApp\Controllers\WeatherForecastController.cs:line 34
14:32:38:732       at lambda_method2(Closure , Object , Object[] )
14:32:38:732       at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
14:32:38:732       at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
14:32:38:732       at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
14:32:38:732       at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
14:32:38:732    --- End of stack trace from previous location ---
14:32:38:732       at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
14:32:38:732       at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
14:32:38:732       at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
14:32:38:732    --- End of stack trace from previous location ---
14:32:38:732       at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
14:32:38:732       at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
14:32:38:732       at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
14:32:38:732       at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
14:32:38:732       at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
14:32:38:732       at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
14:32:38:732       at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
14:32:38:732       at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
14:32:58:734    The thread 0x3458 has exited with code 0 (0x0).
xuejmnet commented 1 year ago

@wanghucheng66 看错误应该是Concurrent并发异常你是否有并发字段比如ConcurrentToken或者Version版本号字段

DbUpdateConcurrencyException: The database operation was expected to affect 1 row(s), but actually affected 0 row(s);

提示应该只有一条受影响但是现在是0条受些影响,是否有重写过SaveChange如果有那么请重新带入参bool的SaveChange而不是无参数的

wanghucheng66 commented 1 year ago

感谢快速的回复!!! Sharding-core相关的配置项如下. CDMSContext中没有重载SaveChange. 刚才发现把.UseLazyLoadingProxies() 都去掉就可以正常更新了. 我这个懒加载配置是不是配置有问题?

`///

/// 配置分表组件 /// /// public static void UseShardingCore(this WebApplicationBuilder builder) { if (!int.TryParse(builder.Configuration["DatabaseCommandTimeout"], out DatabaseCommandTimeout)) { DatabaseCommandTimeout = 300; } builder.Services.AddShardingDbContext().UseRouteConfig(op => { op.AddShardingTableRoute();

        }).UseConfig((provider, op) =>
        {
            op.MaxQueryConnectionsLimit = Environment.ProcessorCount;
            op.CacheModelLockConcurrencyLevel = 1024;
            op.CacheEntrySize = 10;
            op.CacheModelLockObjectSeconds = 30;
            op.CheckShardingKeyValueGenerated = false;
            //当无法获取路由时会返回默认值而不是报错
            op.ThrowIfQueryRouteNotMatch = false;

            op.UseShardingQuery((conStr, builder) =>
            {
                builder
                .UseLazyLoadingProxies()
                .UseSqlServer(conStr);
            });
            op.UseExecutorDbContextConfigure((builder) =>
            {
                builder
                .UseLazyLoadingProxies()
                .UseSqlServer(sqlServerBuilder)
                .UseLoggerFactory(efLogger);
            });
            op.UseShardingTransaction((connection, builder) =>
            {
                builder
                .UseLazyLoadingProxies()
                .UseSqlServer(connection, sqlServerBuilder)
                .UseLoggerFactory(efLogger);
            });
            op.AddDefaultDataSource(CDMSContext.DefaultDataSource, APISystemCommonConfig.DataBaseConnection);

            var serviceProvider = builder.Services.BuildServiceProvider();
            var eventLogger = serviceProvider.GetService<ILogger<CDMSContext>>();

        }).AddShardingCore();`
xuejmnet commented 1 year ago

应该是这个代理问题导致的

xuejmnet commented 1 year ago
image
.UseConfig((sp, o) =>
                {
                    //尝试添加一下这个试试,但是不一定可以,因为你主要还是并发字段的多次修改导致的应该是
                    o.UseEntityFrameworkCoreProxies = true;

                    o.UseShardingQuery((conStr, builder) =>
                    {
                        builder.UseMySql(conStr, new MySqlServerVersion(new Version()));
                    });
                    o.UseShardingTransaction((connection, builder) =>
                    {
                        builder
                            .UseMySql(connection, new MySqlServerVersion(new Version()));
                    });
                })
wanghucheng66 commented 1 year ago

非常感谢. 可以关掉这个issue了. 增加这一行配置之后就可以了. o.UseEntityFrameworkCoreProxies = true;