MySql.Data.MySqlClient.MySqlException:重复的条目

时间:2019-05-30 19:00:25

标签: c# mysql asp.net-core entity-framework-core asp.net-core-identity

如何通过.net身份代码从此自动支架中获得重复的输入错误:

        public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {  UserName = Input.Email, Email = Input.Email };
                var result = await _userManager.CreateAsync(user, Input.Password);
                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                        $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    await _signInManager.SignInAsync(user, isPersistent: false);
                    return LocalRedirect(returnUrl);
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return Page();
        }

产生此堆栈跟踪:

  

Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware [1]         执行请求时发生未处理的异常。   Microsoft.EntityFrameworkCore.DbUpdateException:更新条目时发生错误。有关详细信息,请参见内部异常。 ---> MySql.Data.MySqlClient.MySqlException:键'PRIMARY'的重复条目'3ab1a765-c575-4a50-ba42-6d282ccb24a6'---> MySql.Data.MySqlClient.MySqlException:重复的条目'3ab1a765-c575-4a50 -ba42-6d282ccb24a6”,用于密钥“ PRIMARY”      在MySqlConnector.Core.ServerSession.TryAsyncContinuation(Task 1 task) in C:\projects\mysqlconnector\src\MySqlConnector\Core\ServerSession.cs:line 1252 at System.Threading.Tasks.ContinuationResultTaskFromResultTask 2.InnerInvoke()      在System.Threading.ExecutionContext.RunInternal(ExecutionContext executeContext,ContextCallback回调,对象状态)   ---从之前引发异常的位置开始的堆栈结束跟踪---      在System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task&currentTaskSlot)   ---从之前引发异常的位置开始的堆栈结束跟踪---      在C:\ projects \ mysqlconnector \ src \ MySqlConnector \ Core \ ResultSet.cs:line 43中的MySqlConnector.Core.ResultSet.ReadResultSetHeaderAsync(IOBehavior ioBehavior)      ---内部异常堆栈跟踪的结尾---      在C:\ projects \ mysqlconnector \ src \ MySqlConnector \ MySql.Data.MySqlClient \ MySqlDataReader.cs:line 81中的MySql.Data.MySqlClient.MySqlDataReader.ActivateResultSet(ResultSet resultSet)      在C:\ projects \ mysqlconnector \ src \ MySqlConnector \ MySql.Data.MySqlClient \ MySqlDataReader.cs:line 307的MySql.Data.MySqlClient.MySqlDataReader.ReadFirstResultSetAsync(IOBehavior ioBehavior)      在C:\ projects \ mysqlconnector \ src \ MySqlConnector \ MySql.Data.MySqlClient \ MySqlDataReader.cs:line 292中的MySql.Data.MySqlClient.MySqlDataReader.CreateAsync(MySqlCommand命令,CommandBehavior行为,ResultSetProtocol resultSetProtocol,IOBehavior ioBehavior)      在C:\ projects \ mysqlconnector \ src \ MySqlConnector \ Core \ TextCommandExecutor.cs:第37行      在Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteAsync(IRelationalConnection连接,DbCommandMethod executeMethod,IReadOnlyDictionary 2 parameterValues, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken) --- End of inner exception stack trace --- at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(DbContext _, ValueTuple 2个参数,CancellationToken cancelledToken)处      在Pomelo.EntityFrameworkCore.MySql.Storage.Internal.MySqlExecutionStrategy.ExecuteAsync [TState,TResult](TState状态,Func 4 operation, Func 4验证成功,CancellationToken cancelledToken)处      在Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IReadOnlyList 1 entriesToSave, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken) at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore 9.CreateAsync(TUser用户,CancellationToken cancelledToken)处      在C:\ Users \ Dropbox \ Code \ chuchubi-backend \ Chuchubi.Data \ MultiTenant \ TenantUserStore.cs:第30行的Chuchubi.Data.MultiTenant.TenantUserStore.CreateAsync(ApplicationUser用户,CancellationToken cancelleToken)      在Microsoft.AspNetCore.Identity.UserManager 1.CreateAsync(TUser user) at Microsoft.AspNetCore.Identity.UserManager 1.CreateAsync(TUser用户,字符串密码)处      在C:\ Users \ Dropbox \ Code \ chuchubi-backend \ Chuchubi \ Areas \ Identity \ Pages \ Account \ Register.cshtml.cs:line 71中的Chuchubi.Areas.Identity.Pages.Account.RegisterModel.OnPostAsync(String returnUrl)      在Microsoft.AspNetCore.Mvc.RazorPages.Internal.ExecutorFactory.GenericTaskHandlerMethod.Convert [T](Object taskAsObject)      在Microsoft.AspNetCore.Mvc.RazorPages.Internal.ExecutorFactory.GenericTaskHandlerMethod.Execute(对象接收器,Object []参数)      在Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeHandlerMethodAsync()      在Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeNextPageFilterAsync()      在Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.Rethrow(PageHandlerExecutedContext上下文)      在Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.Next(State&next,Scope&scope,Object&state,Boolean&isCompleted)      在Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeInnerFilterAsync()      在Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()      在Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext上下文)      在Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(状态和下一个,范围和范围,对象和状态,布尔值和已完成)      在Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()      在Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()      在Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)      在Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext上下文)      在Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext上下文)      在SaasKit.Multitenancy.Internal.TenantResolutionMiddleware 1.Invoke(HttpContext context, ITenantResolver 1个tenantResolver处)      在Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext上下文)      在Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext上下文)      在Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)      在Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)      在Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext上下文)   信息:Microsoft.AspNetCore.Hosting.Internal.WebHost [2]

这是来自Visual Studio的自动生成的代码。

编辑:

MySql版本详细信息:

'immediate_server_version', '999999'
'innodb_version', '8.0.16'
'original_server_version', '999999'
'protocol_version', '10'
'slave_type_conversions', ''
'tls_version', 'TLSv1,TLSv1.1,TLSv1.2'
'version', '8.0.16'
'version_comment', 'MySQL Community Server - GPL'
'version_compile_machine', 'x86_64'
'version_compile_os', 'Win64'
'version_compile_zlib', '1.2.11'

我的csproj:

    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.2.4" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.3" />
    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="2.2.0" />
    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql.Design" Version="1.1.2" />
    <PackageReference Include="SaasKit.Multitenancy" Version="1.1.4" />

这是在一个空数据库上完成的,出现错误后,没有用户插入数据库!

1 个答案:

答案 0 :(得分:0)

好吧,试图在一个干净的项目中复制它,我设法弄清楚了。 因此,该应用程序是多租户的,每个身份用户与一个租户都有一对一的关系。

我使用SaasKit将数据库模型Tenant缓存到内存中,同时创建新用户,如下所示:

IdentityUser.Tenant = cachedTenant;
DbContext.SaveChanges();

Entityframework将租户视为新的租户(未跟踪),因此导致消息重复。

所以重复的消息实际上是给新租户的。

通过缓存“视图模型”而不是数据库模型来修复。