[英]Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException
https://localhost:44322/api/Rentals/update when I run the statement, I encounter such an error on the backend side. https://localhost:44322/api/Rentals/update 当我运行语句时,我在后端遇到这样的错误。
'Database operation expected to affect 1 row(s) but actually affected 0 row(s). '数据库操作预计会影响 1 行,但实际上会影响 0 行。 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
有关了解和处理的信息,请参阅http://go.microsoft.com/fwlink/?LinkId=527962
My EntityRepository is here.我的 EntityRepository 在这里。
public void Update(TEntity entity)
{
using (TContext context = new TContext())
{
var updatedEntity = context.Entry(entity);
updatedEntity.State = EntityState.Modified;
context.SaveChanges();
}
}
My Sql table is here我的 Sql 表在这里
CREATE TABLE [dbo].[Rentals] (
[RentalId] INT IDENTITY (1, 1) NOT NULL,
[CarId] INT NOT NULL,
[CustomerId] INT NOT NULL,
[RentDate] DATETIME NOT NULL,
[ReturnDate] DATETIME NULL,
CONSTRAINT [PK_RentalId] PRIMARY KEY CLUSTERED ([RentalId] ASC),
CONSTRAINT [FK_Rentals_Cars] FOREIGN KEY ([CarId]) REFERENCES [dbo].[Cars] ([CarId]),
CONSTRAINT [FK_Rentals_Customers] FOREIGN KEY ([CustomerId]) REFERENCES [dbo].[Customers] ([CustomerId])
);```
My Rental Controller is here.我的出租 Controller 在这里。
public IActionResult Update(Rental rental)
{
var result = _rentalService.Update(rental);
if (result.Success)
{
return Ok(result);
}
return BadRequest(result);
}
I'm having a problem with "post" operations, I can't figure out exactly what the problem is.我在“发布”操作方面遇到问题,我无法弄清楚到底是什么问题。
Looks like the primary key RentalId
not set.看起来主键
RentalId
没有设置。 You should check that the RentalId
property of the rental
entity you want to update exists in the database before doing update.在进行更新之前,您应该检查要更新的
rental
实体的RentalId
属性是否存在于数据库中。 Alternatively you could catch the exception and check for non-existing primary key then take action accordingly.或者,您可以捕获异常并检查不存在的主键,然后采取相应措施。
Code fragment example (for the alternative):代码片段示例(供替代):
public async Task<IActionResult> Update(Rental update)
{
_context.Entry(update).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!Exists(update.RentalId))
{
return NotFound();
}
throw;
}
return Updated(update);
}
private bool Exists(int id)
{
return _context.Rental.Any(e => e.RentalId == id);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.