Friday, March 4, 2016

An object with the same key already exists in the ObjectStateManager. (Entity Framework 6.0)

The code below for updating of objects worked with Entity Framework 5 and below. But using this with Entity Framework 6.0 and Castle Windsor as IOC Container, I get an error message with is the title of this post.
1
2
3
4
5
6
7
8
public void Update(BookDetail item)
{
    if(item!= null)
    {
        _context.Entry(item).State = System.Data.Entity.Entitystate.Modified;
        _context.SaveChanges();
    }
}

So to fix this, replace the code above with DBContext.Entry(T Entity).CurrentValues.SetValues(T Entity).
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public void Update(BookDetail item)
{
    if(item != null)
    {
        var result = _context.BookDetails.Find(item.BookSerialNo);
        if (result != null)
        {
            _context.Entry(result).CurrentValues.SetValues(item);
            _context.SaveChanges();
        }
    }
}

0 comments:

Post a Comment