gpt4 book ai didi

c# - 如何在我的新 .Net Core 项目中修复 DbUpdateConcurrencyException?

转载 作者:太空狗 更新时间:2023-10-30 01:12:34 29 4
gpt4 key购买 nike

我正在工作中构建一个新的 .Net Core 2.2 网站并尝试了几种不同的方法,但是在设置 CRUD 模型后使用编辑功能时我收到错误消息。最初我从数据库优先方法开始,然后在尝试编辑项目时收到 DbUpdateConcurrencyException。我假设我的数据库或表有问题,所以开始了一个新项目,从新项目中的模型和上下文创建数据库。

环境:

  • MacOS Mojave
  • Visual Studio for Mac 社区 8.2.3(内部版本 16)
  • SQL Server 数据库
  • .Net 核心 2.2
  • C#

几个月前,我用相同的环境构建了另一个站点,但没有这样做。

创建步骤:

  • dotnet new webapp -o TestSite
  • cd TestSite/
  • dotnet 添加包 Microsoft.EntityFrameworkCore.Design --version 2.2.6
  • dotnet 添加包 Microsoft.EntityFrameworkCore.SqlServer --version 2.2.6
  • dotnet 添加包 Microsoft.EntityFrameworkCore.Tools --version 2.2.6
  • dotnet 添加包 Microsoft.VisualStudio.Web.CodeGeneration.Design --version 2.2.3

检查网站运行是否正常

  • 网络运行

创建模型和上下文

文件集.cs

using System;
using System.ComponentModel.DataAnnotations;

namespace TestSite.Models
{
public class Fileset
{
public long Id { get; set; }
public string Ticket { get; set; }
public string Requester { get; set; }

[Display(Name = "Research Centre")]
public string ResearchCentre { get; set; }

[Display(Name = "Project ID")]
public string ProjectId { get; set; }

[Display(Name = "Title")]
public string ProjectTitle { get; set; }

[Display(Name = "Name")]
public string Name { get; set; }

[Display(Name = "Internal ID")]
public string InternalId { get; set; }

public string Email { get; set; }

[Display(Name = "Start Date")]
public DateTime StartDate { get; set; }

[Display(Name = "End Date")]
public DateTime EndDate { get; set; }

[Display(Name = "Quota (GB)")]
public long Quota { get; set; }

[Display(Name = "UNC Path")]
public string StoragePath { get; set; }

[Display(Name = "AD Group")]
public string Adgroup { get; set; }

[Timestamp]
public byte[] RowVersion { get; set; }
}
}

TestSiteContext.cs

using System;
using Microsoft.EntityFrameworkCore;

namespace TestSite.Data
{
public class TestSiteContext : DbContext
{
public TestSiteContext (DbContextOptions<TestSiteContext> options) : base(options)
{
}

public DbSet<Models.Fileset> Fileset { get; set; }
}
}

更新 Startup.cs 以包含数据库的连接字符串引用

services.AddDbContext<Data.TestSiteContext>(options => options.UseSqlServer(Configuration.GetConnectionString("TestDB")));

将连接字符串添加到 appsettings.json

"ConnectionStrings": {
"TestDB": "Server=server;Database=database;Integrated Security=SSPI;Connection Timeout=15"
}

搭建模型

  • dotnet aspnet-codegenerator razorpage -m Fileset -dc TestSite.Data.TestSiteContext -udl -outDir Pages/Filesets --referenceScriptLibraries

初始迁移

  • dotnet ef 迁移添加 InitialCreate
  • dotnet ef 数据库更新

确认数据库有新表和正确的模式,并且在 dotnet cli 输出中没有报告创建错误

  • 网络运行

导航到 https://localhost:5001/Filesets在 kestrel 服务器上,创建一个新项目并确认它出现在 SQL 数据库中

  • 尝试了该项目的“编辑”页面*

错误

DbUpdateConcurrencyException: Database operation 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.
Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ThrowAggregateUpdateConcurrencyException(int commandIndex, int expectedRowsAffected, int rowsAffected)
Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ConsumeResultSetWithPropagationAsync(int commandIndex, RelationalDataReader reader, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ConsumeAsync(RelationalDataReader reader, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(DbContext _, ValueTuple<IEnumerable<ModificationCommandBatch>, IRelationalConnection> parameters, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync<TState, TResult>(TState state, Func<DbContext, TState, CancellationToken, Task<TResult>> operation, Func<DbContext, TState, CancellationToken, Task<ExecutionResult<TResult>>> verifySucceeded, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IReadOnlyList<InternalEntityEntry> entriesToSave, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken)
TestSite.Pages.Filesets.EditModel.OnPostAsync() in Edit.cshtml.cs
-
}
_context.Attach(Fileset).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync(); // Error line
}
catch (DbUpdateConcurrencyException)
{
if (!FilesetExists(Fileset.Id))
{
return NotFound();
Microsoft.AspNetCore.Mvc.RazorPages.Internal.ExecutorFactory+GenericTaskHandlerMethod.Convert<T>(object taskAsObject)
Microsoft.AspNetCore.Mvc.RazorPages.Internal.ExecutorFactory+GenericTaskHandlerMethod.Execute(object receiver, object[] arguments)
Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeHandlerMethodAsync()
Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeNextPageFilterAsync()
Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.Rethrow(PageHandlerExecutedContext context)
Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

我对此比较陌生,但是在按照教程或在 2.2 版上构建我的第一个站点时,并没有发生这种情况。除了上述步骤外,我没有执行任何其他步骤。我不应该收到我一个人正在测试的东西的并发错误,除非我有意这样做,即打开一个页面进行编辑,在第二页上编辑项目,然后返回尝试编辑第一页。

有人可以帮忙吗?我做了什么蠢事吗?主键和行版本值在我的模型中,并在我的 SQL 数据库设计中正确显示。

如果您需要更多信息,请告诉我。

更新

按要求添加了 Edit.cshtml.cs 的代码。

public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}

_context.Attach(Fileset).State = EntityState.Modified;

try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!FilesetExists(Fileset.Id))
{
return NotFound();
}
else
{
throw;
}
}

return RedirectToPage("./Index");
}

我还没有修改它,所以应该是默认的,由脚手架过程创建。

更新 2

在 Neil 的回答和下面的评论之后,我更新了我的 OnPostAsync 方法。

[BindProperty]
public Fileset Fileset { get; set; }
public SelectList FilesetSL { get; set; }

public async Task<IActionResult> OnPostAsync(int id)
{
if (!ModelState.IsValid)
{
return Page();
}

_context.Attach(Fileset).State = EntityState.Modified;

var filesetToUpdate = await _context.Fileset
.FirstOrDefaultAsync(m => m.Id == id);

if (filesetToUpdate == null)
{
return HandleDeletedFileset();
}

// Update the RowVersion to the value when this entity was
// fetched. If the entity has been updated after it was
// fetched, RowVersion won't match the DB RowVersion and
// a DbUpdateConcurrencyException is thrown.
// A second postback will make them match, unless a new
// concurrency issue happens.
_context.Entry(filesetToUpdate)
.Property("RowVersion").OriginalValue = Fileset.RowVersion;

if (await TryUpdateModelAsync<Fileset>(
filesetToUpdate, "Fileset", f => f.Ticket, f => f.Requester, f => f.ResearchCentre, f => f.ProjectId, f => f.ProjectTitle, f => f.Name, f => f.InternalId,
f => f.Email, f => f.StartDate, f => f.EndDate, f => f.Quota, f => f.StoragePath, f => f.Adgroup))
{
try
{
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
catch (DbUpdateConcurrencyException ex)
{
var exceptionEntry = ex.Entries.Single();
var clientValues = (Fileset)exceptionEntry.Entity;
var databaseEntry = exceptionEntry.GetDatabaseValues();

if (databaseEntry == null)
{
ModelState.AddModelError(string.Empty, "Unable to save. " + "The fileset was deleted by another user");
return Page();
}

var dbValues = (Fileset)databaseEntry.ToObject();
await SetDbErrorMessage(dbValues, clientValues, _context);

// Save the current RowVersion so next postback
// matches unless an new concurrency issue happens.
Fileset.RowVersion = (byte[])dbValues.RowVersion;
// Must clear the model error for the next postback.
ModelState.Remove("Fileset.RowVersion");
}
}

FilesetSL = new SelectList(_context.Fileset, "ID", "Project ID", filesetToUpdate.ProjectId);
return Page();
}

private IActionResult HandleDeletedFileset()
{
var fileset = new Fileset();
// ModelState contains the posted data because of the deletion error and will overide the Department instance values when displaying Page().
ModelState.AddModelError(string.Empty,
"Unable to save. The Fileset was deleted by another user.");
FilesetSL = new SelectList(_context.Fileset, "ID", "Project ID", fileset.ProjectId);
return Page();
}

private async Task SetDbErrorMessage(Fileset dbValues, Fileset clientValues, TestSiteContext context)
{
if (dbValues.Ticket != clientValues.Ticket)
{
ModelState.AddModelError("Fileset.Ticket",
$"Current value: {dbValues.Ticket}");
}
if (dbValues.Requester != clientValues.Requester)
{
ModelState.AddModelError("Fileset.Requester",
$"Current value: {dbValues.Requester}");
}
if (dbValues.ResearchCentre != clientValues.ResearchCentre)
{
ModelState.AddModelError("Fileset.ResearchCentre",
$"Current value: {dbValues.ResearchCentre}");
}
if (dbValues.ProjectId != clientValues.ProjectId)
{
ModelState.AddModelError("Fileset.ProjectId",
$"Current value: {dbValues.ProjectId}");
}
if (dbValues.ProjectTitle != clientValues.ProjectTitle)
{
ModelState.AddModelError("Fileset.ProjectTitle",
$"Current value: {dbValues.ProjectTitle}");
}
if (dbValues.Name != clientValues.Name)
{
ModelState.AddModelError("Fileset.Name",
$"Current value: {dbValues.Name}");
}
if (dbValues.InternalId != clientValues.InternalId)
{
ModelState.AddModelError("Fileset.InternalId",
$"Current value: {dbValues.InternalId}");
}
if (dbValues.Email != clientValues.Email)
{
ModelState.AddModelError("Fileset.Email",
$"Current value: {dbValues.Email}");
}
if (dbValues.StartDate != clientValues.StartDate)
{
ModelState.AddModelError("Fileset.StartDate",
$"Current value: {dbValues.StartDate}");
}
if (dbValues.EndDate != clientValues.EndDate)
{
ModelState.AddModelError("Fileset.EndDate",
$"Current value: {dbValues.EndDate}");
}
if (dbValues.Quota != clientValues.Quota)
{
ModelState.AddModelError("Fileset.Quota",
$"Current value: {dbValues.Quota}");
}
if (dbValues.StoragePath != clientValues.StoragePath)
{
ModelState.AddModelError("Fileset.StoragePath",
$"Current value: {dbValues.StoragePath}");
}
if (dbValues.Adgroup != clientValues.Adgroup)
{
Fileset fileset = await context.Fileset
.FindAsync(dbValues.Adgroup);
ModelState.AddModelError("Fileset.Adgroup",
$"Current value: {fileset?.Adgroup}");
}

ModelState.AddModelError(string.Empty,
"The record you attempted to edit "
+ "was modified by another user after you. The "
+ "edit operation was canceled and the current values in the database "
+ "have been displayed. If you still want to edit this record, click "
+ "the Save button again.");
}

结果是:

您尝试编辑的记录已被您之后的另一用户修改。编辑操作已取消,数据库中的当前值已显示。如果您仍想编辑此记录,请再次单击“保存”按钮。

我可以毫无问题地创建和删除记录,但编辑一直遇到并发问题。即使是第二次回发也不起作用。

最佳答案

问题是 Edit.cshtml 文件中没有引用 RowVersion。

<input type="hidden" asp-for="Fileset.RowVersion" />

Handling Concurrency Conflicts

关于c# - 如何在我的新 .Net Core 项目中修复 DbUpdateConcurrencyException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58238623/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com