Be mindful of your DataContext's "context"

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.  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:

!(/images/michelotti/118022/dc8fbd50-r_diagram.jpg)

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:

!(/images/michelotti/118022/756a42bb-r_ReferenceDataContext.jpg)

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!

posted on Thursday, December 27, 2007 8:48 PM Print

This article is part of the GWB Archives. Original Author: Steve Michelotti

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.