我正在建立一个新的.Net Core 2.2网站,并尝试了几种不同的方法,但是在设置CRUD模型后使用“编辑”功能时出现错误。最初,我从数据库优先方法开始,然后在尝试编辑项目时收到DbUpdateConcurrencyException。我以为数据库或表有问题,所以开始了一个新项目,该项目从新项目中的模型和上下文创建数据库。
环境:
几个月前,我用另一个没有这个环境的网站构建了一个站点。
创建步骤:
检查网站是否正常
创建模型和上下文
Fileset.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以包括DB的连接字符串引用
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输出中未报告创建错误
在kestrel服务器上导航到https://localhost:5001/Filesets,创建一个新项目并确认它已出现在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 DB设计中正确显示。
如果您需要更多信息,请告诉我。
更新
根据要求添加了 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.");
}
这将导致:
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.
我可以创建和删除记录,没有任何问题,但是“编辑”一直在遇到并发问题。甚至第二次回发也不起作用。
答案 0 :(得分:4)
问题在于 Edit.cshtml 文件中未引用RowVersion。
<input type="hidden" asp-for="Fileset.RowVersion" />
答案 1 :(得分:0)
如果这确实是脚手架创造的,那是一个非常糟糕的例子。尝试加载记录,进行修改然后保存。
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
var record = _context.Fileset.Find(id); // <-- id should be part of the POST
record.Ticket = "Some random text";
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!FilesetExists(Fileset.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToPage("./Index");
}