Donate

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();
        }
    }
}

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.