Patee Gutee
Patee Gutee

Reputation: 304

Error Saving Model when Key has changed by user

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

Answers (3)

David Browne - Microsoft
David Browne - Microsoft

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

Serge
Serge

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

Dionis Takac
Dionis Takac

Reputation: 91

This error can mean some of these things:

  • as error suggests, it could be that entity was modified since you take it from database (concurrency)
  • it is possible that your database doesn't contain entity with that ID
  • it could be that you use 2 different DBContext in your solution

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

Related Questions