- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在工作中构建一个新的 .Net Core 2.2 网站并尝试了几种不同的方法,但是在设置 CRUD 模型后使用编辑功能时我收到错误消息。最初我从数据库优先方法开始,然后在尝试编辑项目时收到 DbUpdateConcurrencyException。我假设我的数据库或表有问题,所以开始了一个新项目,从新项目中的模型和上下文创建数据库。
环境:
几个月前,我用相同的环境构建了另一个站点,但没有这样做。
创建步骤:
检查网站运行是否正常
创建模型和上下文
文件集.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 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" />
关于c# - 如何在我的新 .Net Core 项目中修复 DbUpdateConcurrencyException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58238623/
我正在使用 NetBeans 开发 Java 中的 WebService,并使用 gradle 作为依赖管理。 我找到了this article关于使用 gradle 开发 Web 项目。它使用 Gr
我正在将旧项目从 ant 迁移到 gradle(以使用其依赖项管理和构建功能),并且在生成 时遇到问题>eclipse 项目。今天的大问题是因为该项目有一些子项目被拆分成 war 和 jar 包部署到
我已经为这个错误苦苦挣扎了很长时间。如果有帮助的话,我会提供一些问题的快照。请指导我该怎么办????在我看来,它看起来一团糟。 *** glibc detected *** /home/shivam/
我在 Ubuntu 12.10 上运行 NetBeans 7.3。我正在学习 Java Web 开发类(class),因此我有一个名为 jsage8 的项目,其中包含我为该类(class)所做的工作。
我想知道 Codeplex、GitHub 等中是否有任何突出的项目是 C# 和 ASP.NET,甚至只是 C# API 与功能测试 (NUnit) 和模拟(RhinoMocks、NMock 等)。 重
我创建了一个 Maven 项目,包装类型为“jar”,名为“Y”我已经完成了“Maven 安装”,并且可以在我的本地存储库中找到它.. 然后,我创建了另一个项目,包装类型为“war”,称为“X”。在这
我一直在关注the instructions用于将 facebook SDK 集成到我的应用程序中。除了“helloFacebookSample”之外,我已经成功地编译并运行了所有给定的示例应用程序。
我想知道,为什么我们(Java 社区)需要 Apache Harmony 项目,而已经有了 OpenJDK 项目。两者不是都是在开源许可下发布的吗? 最佳答案 事实恰恰相反。 Harmony 的成立是
我正在尝试使用 Jsoup HTML Parser 从网站获取缩略图 URL我需要提取所有以 60x60.jpg(或 png)结尾的 URL(所有缩略图 URL 都以此 URL 结尾) 问题是我让它在
我无法构建 gradle 项目,即使我编辑 gradle 属性,我也会收到以下错误: Error:(22, 1) A problem occurred evaluating root project
我有这个代码: var NToDel:NSArray = [] var addInNToDelArray = "Test1 \ Test2" 如何在 NToDel:NSArray 中添加 addInN
如何在单击显示更多(按钮)后将主题列表限制为 5 个(项目)。 还有 3(项目),依此类推到列表末尾,然后它会显示显示更少(按钮)。 例如:在 Udemy 过滤器选项中,当您点击查看更多按钮时,它仅显
如何将现有的 Flutter 项目导入为 gradle 项目? “导入项目”向导要求 Gradle 主路径。 我有 gradle,安装在我的系统中。但是这里需要设置什么(哪条路径)。 这是我正在尝试的
我有一个关于 Bitbucket 的项目。只有源被提交。为了将项目检索到新机器上,我在 IntelliJ 中使用了 Version Control > Checkout from Ve
所以,我想更改我公司的一个项目,以使用一些与 IDE 无关的设置。我在使用 Tomcat 设置 Java 应用程序方面有非常少的经验(我几乎不记得它是如何工作的)。 因此,为了帮助制作独立于 IDE
我有 2 个独立的项目,一个在 Cocos2dx v3.6 中,一个在 Swift 中。我想从 Swift 项目开始游戏。我该怎么做? 我已经将整个 cocos2dx 项目复制到我的 Swift 项目
Cordova 绝对是新手。这些是我完成的步骤: checkout 现有项目 运行cordova build ios 以上生成此构建错误: (node:10242) UnhandledPromiseR
我正在使用 JQuery 隐藏/显示 li。我的要求是,当我点击任何 li 时,它应该显示但隐藏所有其他 li 项目。当我将鼠标悬停在文本上时 'show all list item but don
我想将我所有的java 项目(223 个项目)迁移到gradle 项目。我正在使用由 SpringSource STS 团队开发的 Gradle Eclipse 插件。 目前,我所有的 java 项目
我下载this Eclipse Luna ,对于 Java EE 开发人员,如描述中所见,它支持 Web 应用程序。我找不到 file -> new -> other -> web projects
我是一名优秀的程序员,十分优秀!