.netentity-frameworkobjectstatemanager

Why do I get referenced entities added to context instead of attached, unchanged?


I have attached entities to a context with EntityState.Unchanged which will be referenced by a new entity I add later via DbContext<T>.Add(). The Add() adds the entity, but it also adds the other entities it references to the added collection in ObjectStateManager, despite the referenced ones being in the unchanged collection previously. Under the debugger I see the referenced entities in both collections. So, I end up with inserts occurring on the referenced children entities when I don't want them to.


Solution

  • The previously attached entities were identical structurally, but they were different references. EF seems to use ReferenceEquals under the covers.