0

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.

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

whilst not spot on (couldn't use Find() afterward but simply checked the count of players returned by that ID) - its done what it needed to do, thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.