1

Is it possible (this is an EF6 DbContext using CodeFirst) to detect any entities that have been passed to a given data context for saving but are actually attached to a different context?

Entity framework just gives a generic, cannot save because entities are attached to another context error, but doesn't give any information about which entity is attached to a different context. This makes this situation particularly hard to debug.

I know about changeTracker.Entries() (of which I'm not sure these records actually appear in), and I know I can compare the entities of this against the local context to see if they are tracked, but neither of these options seem to allow me to determine whether the entity is being tracked by a different context.

gmn
  • 4,199
  • 4
  • 24
  • 46
  • 2
    Might this be of use? http://stackoverflow.com/questions/25230024/get-dbcontext-from-entity-in-entity-framework – bigozz Mar 03 '17 at 10:35

1 Answers1

1

You cannot do that, because the entity does not store any pointer to the context, it's actually the other way around (the context knows the entity). What you can do, if you are using lazy loading in your entities, is, using reflection, find out the context from which the entity came from. But I wouldn't advise it.

Ricardo Peres
  • 13,724
  • 5
  • 57
  • 74