I have moved my active blog over to tumblr. I've maintained this blog for reference but will be posting to http://www.robustsoftware.co.uk instead. I've pointed my Feedburner feed to tumblr so if you're subscribed already you should already have switched with me.

Clearing the cache of a LINQ to SQL DataContext

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.