Given the code that I omitted from the question, behind the comment
// update existing's properties with those in @case
I'm not surprised no one could answer.
The problem was that, in that block of omitted code:
existing.Events.Add(new Event
{
CaseId = @case.Id,
Author = user,
Text = existing.GetChangeDescription(@case),
DateTime = now,
EventType = EventType.Update
});
I am setting up an association to the User object, Entity Framework will subsequently set it's state to added, which is fair enough as there is no trace of this user loaded in the context at this stage, and even if there was, I'd get a different "cannot track object of same type with same key" error. The best approach would be to either:
- Load the user from the database using DbSet.Find, setting the passed in user to this loaded user
- Don't set the navigation property, leaving it null and set the AuthorId on the Event object instead
- Do something smart whereby the context is queried to see if the user already is loaded and if not attaches the passed user to the context with State = EntityState.Unchanged (similar to the first option only avoiding the database hit)
I have gone for option 1 because it fits best with my current architecture, however I'm looking at refactoring to make option 3 possible.