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.

2 comments:
You should either throw away the DataContext or use the Refresh method. Relying on private methods to achieve undocumented behavior is not recommended.
In most situations (i.e. non-test) I'd agree and I tried using Refresh but it was either failing or not having the desired effect. I can't remember which now.
Post a Comment