Be mindful of your DataContext's "context"

In a previous post here, I discussed implementation of Attaching Linq entities to a DataContext.  In that post, I showed an implementation of utilizing a Detach() method that I originally based on this post here.  The implementation boils down to the need to reset EntityRef<> references back to their default - otherwise, it will try to attach the parent objects (which is often not the goal of your code as this is often just reference data). Consider the DataContext below:

The fundamental problem here is that State and AddressType should NOT be in this data context at all!  Doing so causes the auto-generated classes to include EntityRef<> references to them in the Address class.  In my actual Address business objects, all I really care about it the StateID.  The database takes care of enforcing the foreign key to the State table.  My application does need to query the State table directly for populating the State drop down list but it should be in its own data context.  So I need to have 2 different DataContexts.  The first should contain only Contact and Address from the diagram above. The second (call it ReferenceDataContext for my State and AddressType reference data) should simply look like this:

Bottom line: don't stuff everything in your database into a single DataContext dumping ground - be mindful of the context.  If you have a DataContext where the only items you're updating contain business entity and not their reference data then do not include them - this is much simplier and allows you to avoid having to write Detach() methods at all!

Tweet Post Share Update Email RSS