Hi DenisK,
Thanks for your response. By views I do mean UI views. Sorry, my previous post wasn't very clear.
I've since found out a little bit more about the problem. We have a very large Domain Model with hundreds of entities, and the problematic scenario is as follows:
We have queried up a main entity and some of its related entities into the EntityManager, and the user decides to run a procedure to effectively recalculate some data - thus making the current related entities stale. The code that does this is in a service that is completely separate from the main application. When this service does its calculations, it creates new related entities for the main entity and saves them in the DB.
Once this service is done, the main application then has to retrieve the entities from the DB again. The problem is that the entity manager doesn't know that the current related entities are now bogus.
The code currently only removes a hand full of the related entities in the entire graph - the ones we think need to get removed because they have been since regenerated by the other service and need to be re-fetched - although there could be other entities we need to remove (but writing code to create entity spans and to remove all the possible related entities would be huge and could change often).
So to recap - we have a Main entity and some of its related entities in the EntityManager, we invoke a separate service to recalculate some data, which consequently invalidates some of our data in the cache, so we remove the entities that we think should be removed, and we refetch the entities into the cache.
Meanwhile, there is another view that shares some of this data (I know I know - we're in a world of hurt at this point). The user needs to be able to use both views at the same time. After some entities were removed and subsequently refreshed, the user does some searching on the other view and more related entities are brought back from the DB. The user tries to save, and you get the exception that I mentioned in the first post.
The thing is - I've narrowed it down to a single entity - because after it throws the "The object being attached to the source object is not attached to the same ObjectContext as the source object." exception while trying to save, as part of our "Close the View" code, we call Manager.RejectChanges - and that throws an exception and says
An entity with this key: (insert our Entity Type here): 64334 (our entity key) already exists in this EntityManager.
So how did it end up in the Entity Manager twice? I thought this wasn't possible? And is there an easy way to walk an entire graph and ensure we are removing all the related entities?
Hope this makes sense.
Thanks!