Reputation: 304
I have a model using string as key instead of Id.
public class Item
{
[Key]
public string SerialNo { get; set; }
However, I am having issue saving:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Item model)
{
if (ModelState.IsValid)
{
_db.Entry(model).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
I am getting the error when updating a record and changing SerialNo value:
Store update, insert, or delete statement affected an unexpected number of rows... Entities may have been modified or deleted since entities were loaded.
Upvotes: 0
Views: 74
Reputation: 89396
like the error only occurs when I edit a record and change the SerialNo field
You can’t update the key in EF, and you normally shouldn’t update the primary key anyway.
If you really need to you can use a raw SQL query, or delete, SaveChanges(), insert.
Upvotes: 2
Reputation: 43959
Try this
existedItem = _db.Set<Item>().FirstOrDefault( i=> i.SerialNo == model.SerialNo );
if (existedItem != null)
{
_db.Entry(existedItem).CurrentValues.SetValues(model);
_db.SaveChanges();
}
Upvotes: 1
Reputation: 91
This error can mean some of these things:
These are some of things which are possible.
I wanted to leave comment but I don't have reputation to do that so I answered directly.
Upvotes: 2