Clearing the cache of a LINQ to SQL DataContext
Posted by Garry Shutler in Extension methods, LINQ, Unit testing
I was having some problems with my test code in that the DataContext was returning the objects from the cache (even though it was querying the database) and this was skewing my integration tests. Through the use of Reflector I found that there actually is a method for clearing the cache, handily called ClearCache(). However, the method was internal and so could not be called directly from code.
Internal methods are, however, available through reflection (I'm a bit of a noob when it comes to reflection so there might be constraints on when they are and when they aren't but this works for me). In order to make it easy to clear the cache (for example, after saving but before retrieving the object from the database for checking it saved correctly) I have created an extension method to do the heavy lifting for me:
public static void ClearCache(this ProjectSupportContext context)
{
const BindingFlags FLAGS = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
var method = context.GetType().GetMethod("ClearCache", FLAGS);
method.Invoke(context, null);
}
Hope this helps someone else out with LINQ to SQL caching woes.
This entry was posted on at Thursday, November 06, 2008 and is filed under Extension methods, LINQ, Unit testing. You can follow any responses to this entry through the RSS 2.0. You can leave a response.
