views:

36

answers:

1

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?!

A: 

Any update guys?

csharpdev
If you too would like to see an answer to this question you might want to vote up on it.
Eran Betzalel