简体   繁体   中英

EF, Update doesnt work, it says Entities may have been modified or deleted since entities were loaded.

I am trying to create a layered MVC project but I am having an UPDATE problem in EF. I am getting the following error.

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. 

I have DAL and BusinessLayer. In DAL, I have the following code for UPDATE

public void Update(params T[] entities)
{
    using (var context = new BorselDBEntities())
    {
        foreach (T entity in entities)
        {
            context.Entry(entity).State = EntityState.Modified;
        }   
        context.SaveChanges();
    }
}

and this is how I call the DAL from BusinessLayer

public void UpdateProduct(params Product[] products)
{
   _productRepository.Update(products);
}

Why am I getting the error above and what could I do to fix it?

One common reason is that context.Entry(entity) fails to get the entity which you want to update.

When you're debugging, see if context.Entry(entity) returns the entity; easily done by putting it on a separate line and setting a breakpoint afer:

public void Update(params T[] entities)
{
    using (var context = new BorselDBEntities())
    {
        foreach (T entity in entities)
        {
            var myEntity = context.Entry(entity);
            myEntity.State = EntityState.Modified;
        }   
        context.SaveChanges();
    }
}

If it's not, you'll need to work back through your code and work out why it's not able to pick it up. Often this will be because the identity/primary key column is not set on 'entity'.

Eg in an MVC application, if you have an Edit/update form, remember to have a

@Html.HiddenFor(model => model.Id)

It is necessary to call the Attach method on the DbSet for the entity you are updating before you can change it's State. The local DbContext needs to contain the Entity or it will not know what changes to track.

https://msdn.microsoft.com/en-us/library/gg696261(v=vs.103).aspx

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM