Exception when updating rows with Entity Framework

I get the following exception when trying to update my records:

System.InvalidOperationException: An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

The code is as follows: (player is a contract version of player which is passed to method as parameter, ToDbPlayer() is an extension method that takes a contract.Player object and creates an equivalent one for the DB)

using (var context = _contextFactory.CreateEntities())
{
    var dbPlayer = context.Players.Find(player.PlayerId);
    var entity = context.Players.Attach(player.ToDbPlayer()); //here error occurs
    context.Entry(entity).State = dbPlayer == null ? EntityState.Added : EntityState.Modified;
    context.SaveChanges();
}

I'm confused as to what to do - I'm trying to simply update the records in the DB however its falling over when I try to attach it to the context.

I'm not overly confident on my EF skills so if someone can point me in the right direction, it'd be appreciated.

Answers


When you do the find the entity will already be attached, so you will not be able to attach it again.

If you need to get the entity without it being tacked use .AsNoTracking() i.e.

var dbPlayer = context.Players.AsNoTracking().Find(player.PlayerId)

Need Your Help

SQL Server Mangament Studio 2008 unable to connect to SSIS packages on SQL Server 2005

sql-server sql-server-2005 sql-server-2008 ssis

I get an "Class not registered" error whenever I attempt to connect to the integration services on sql server 2005 from within SQL Managment Studio 2008.

How can I avoid a InvalidCastException in .NET?

c# casting .net

Is there a way to check whether a C# cast will be successful? In some cases; based on how a rendered page is put together; inheriting from different Master Pages, some casts will work and others wi...