views:

23

answers:

1

The project I'm working on has quite a lot of "look up" data associated with it. For this reason, on the first instantiation of the class that handles this, I set static IEnumerable's with all the lookup data, thusly:

private static IEnumerable<Kiosk> _kiosks;
private static IEnumerable<Paper> _papers;
private static IEnumerable<NewsAgent> _newsAgents;

And..

if (_kiosks == null)
   _kiosks = db.Kiosks.Where(k => k.Active).OrderBy(k => k.Order).ToList();

if (_papers == null)
   _papers = db.Papers.Where(p => p.Active).OrderBy(p => p.Name).ToList();

if (_newsAgents == null)
   _newsAgents = db.NewsAgents.Where(n => n.Active).OrderBy(n => n.Order).ToList();

Each time this class is instantiated, I create new Linq entities for the data classes I need to save, using a brand new DataContext. When I try to submit these changes I get the following error:

"System.NotSupportedException: An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported."

I gather that the cached lookup data, being created on a separate DataContext, is causing this issue. I would think that it should not matter, as the cached data is persisted with ToList, though at a guess each entity internally saves which DataContext it was generated on.

Having a static DataContext is out of the question, as changes to the data entities in the previous run may not be Submitted. Calling Submit on the datacontext on the second run causes an error where the original entites were not persisted.

How then, can I persist this cached data to be used on a new DataContext?

My assumption is that the cached lookup data has come from a separate

+1  A: 

Don't cache the actual objects returned from the data context in the first place. Cache simple poco objects instead that have the bare minimum information on them, then use the ID values rather than objects when updating:

Employee.Status = cachedStatus;

becomes

Employee.StatusID = cachedStatus.ID;
Neil Barnwell