views:

53

answers:

1

See this scenario:

1-I have a single ObjectContext instance shared between multiple business logic layer classes to avoid identity and tracking problems when using multiple object contexts.

2-An object of a class tries to create and insert an entity but an exception takes places (because of a foreign key constraint, unique key constraint or any other cause).

3-Another object of another class tries to insert another entity that have no problem.

here an exception is thrown because the ObjectContext instance is still keeping track of the first object and tries to insert it once again when SaveChanges() is called.

I know that one solution is to deatach the object that caused the exception when the exception took place, but I want to prevent a situation where a developer writing bad code affects the behavior of other classes in the application.

Any clue?

+2  A: 

It sounds like you're keeping your ObjectContexts around for a long time, and using them across multiple units of work. These long lifespans will introduce precisely the sorts of problems you described. One possible solution to your problem is disposing the ObjectContext when an operation fails, and instantiating a new ObjectContext for the next operation. Note that I am not suggesting using multiple ObjectContexts in the application concurrently. It's difficult to say how your application should be architected without seeing it, but the symptom you described is indicative of trying to use the same ObjectContext for too many things at once.

Craig Stuntz
I agree with this... I think you'll have to reconsider your design.
Gerrie Schenck