views:

26

answers:

2

How can I implement GetItemFromCacheById function, such that it takes object from 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);
}
+1  A: 

You shouldn't rely on LINQ to SQL's internal cache. LINQ to SQL was designed to get you objects from the database and to submit the changes back to the database. It is not intended to be a mid-tier caching component although, internally, it does have certain cache behaviors. (reference)

Why do you need cached entities in this case? Do you need an unchanged version of an entity? Are you concerned with performance?

bruno conde
Actually I don't know of any practical application for this. Just trying to better understand posibilities.
alex2k8
+1  A: 

The reason why it's not working as you posted is because of a small bug in linq to sql. You must place your lambda expression to filter inside the Single method itself, like this:

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.

Otter