4

I have a database with a bunch of reference tables like States, Languages, etc.. I would like to be able to cache these tables and then use those types in any ObjectContext I want. So in pseudo code I want to be able to do something like this

var db1 = new PatientObjectContext();
Cache.CacheStates(db1.States.ToList())

var person = new Person { State = Cache.GetState("PA")} ;
var db2 = new PatientObjectContext();

db2.People.Add(person)
db2.SaveChanges();

I saw this blog post (http://blogs.msdn.com/b/alexj/archive/2009/04/22/tip-14-caching-entity-framework-reference-data.aspx). But this didn't apply to me because I think it is not using POCO's. When I try to attach the cached object to the objectContext, I get an exception because an object with that primary key is already in that contexts states collection.

It seems that caching reference tables should be a pretty common problem, but I cant seem to find any straight forward solutions for this.

Jacob
  • 3,598
  • 4
  • 35
  • 56
Vadim Rybak
  • 1,677
  • 20
  • 25

2 Answers2

0

Alex's post is every bit as relevant to POCO entities as to non-POCOs. Why do you think it isn't?

Craig Stuntz
  • 125,891
  • 12
  • 252
  • 273
  • You are right it is valid, but it does not mention that you can get an exception if you try to attach a cloned object to the same context more then once. This is what was giving me problems – Vadim Rybak Aug 18 '10 at 17:32
0

I figured out what I was doing wrong. Before attaching the cloned cached object to the new context I needed to make sure that it is not already attached. Because attaching the same object 2 times was throwing an exception. So I found some code that lets me check if an Item is already in the context before attaching it.

Is is possible to check if an object is already attached to a data context in Entity Framework?

Community
  • 1
  • 1
Vadim Rybak
  • 1,677
  • 20
  • 25