How to cache L2E entity without attach/detach?
Posted
by Eran Betzalel
on Stack Overflow
See other posts from Stack Overflow
or by Eran Betzalel
Published on 2010-04-13T22:25:17Z
Indexed on
2010/04/14
8:43 UTC
Read the original article
Hit count: 408
The following code will select a key/value table in the DB and will save the result to the cache:
using (var db = new TestEntities())
{
if(Cache["locName_" + inventoryLocationName] != null)
return Cache["locName_" + inventoryLocationName];
var location =
db.InventoryLocationsSet.FirstOrDefault(
i => i.InventoryLocationName.Equals(
inventoryLocationName,
StringComparison.CurrentCultureIgnoreCase));
db.Detach(location); // ????
Cache["locName_" + inventoryLocationName] = location;
return location;
}
But it doesn't work well when I'm trying to use the cached object. Of course, the problem is the different ObjectContext
, so I use Attach/Detach and then the problem solves but with a codding horror price:
db.Attach(locationFromCache); // ????
try
{
// Use location as foreign key
db.SaveChanges();
}
finally
{
db.Detach(locationFromCache); // ????
}
So, how can I use cached objects without using attach/detach methods?
What happens if more than one user will have to use this cached object? Should I put the whole thing in a CriticalSection?!
© Stack Overflow or respective owner