https://localhost:44322/api/Rentals/update when I run the statement, I encounter such an error on the backend side.
'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
My EntityRepository is here.
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
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.
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. You should check that the RentalId
property of the rental
entity you want to update exists in the database before doing update. 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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.