Sql – LINQ to SQL DataContext Caching

linq-to-sql

I am using Linq to SQL as my DAL layer and during unit test I found out that my objects are not being returned from database but from the DataContext cache.

The strange thing is that when the objects are returned from the cache why does it require a separate call to the database to fetch all the fields.

Anyway, I implemented a ClearCache method that will clear out the cache. But I am only clearing the cache in the unit test and not in the API code.

The reason is that once the object is inserted it is good to load from the cache then to fetch it again from the database.

What do you think?

UPDATE:

public static void ClearCache(this EStudyModelDataContext context)
        {
            const BindingFlags Flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
            var method = context.GetType().GetMethod("ClearCache", Flags);
            method.Invoke(context, null);
        }

Best Answer

You are correct that L2S will return items from the cache when it can. I learned about this the hard way. A clean way to handle this is to do a context.RefreshRow after each Insert and Update operation. This refreshes the cache and guarantees the cache is current.

Related Topic