Get cached Entity by ID without calling db

How can I implement the GetItemFromCacheById function so that it takes the object from the linq-to-sql cache instead of calling the database.

using (var cxt = new DbDataContext())
{
    // Read item into the cache
    Item item = cxt.Items.Where(x => x.Id == 1).Single();

    //...

    item = GetItemFromCacheById(cxt, 1);
}

      

+2


source to share


2 answers


The reason it doesn't work as you posted this is because of a small bug in linq for sql. You should put your filtering lambda expression inside the Single method itself, like so:

Item item = cxt.Items.Single (x => x.Id == 1);



According to this site the bug will be fixed in .net 4.0 http://damieng.com/blog/2009/06/01/linq-to-sql-changes-in-net-40 .

+1


source


You shouldn't rely on LINQ to SQL internal cache. LINQ to SQL was designed to get objects from the database and send changes back to the database. It is not intended to be a middle-tier caching component, although internally it has certain cache behavior. ( link )



Why do you need cached objects in this case? Need an immutable version of an object? Are you interested in productivity?

+1


source







All Articles