tags:

views:

143

answers:

1

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);
        }
+1  A: 

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.

Randy Minder
Updated post! I have a ClearCache method. I think the L2S cache does not cache the entire object but only the identity of the object. That is why it fetches the object from the database. I may be wrong! Also, I think I only want to do this in unit test and not in actual code. I accomplished it by using Repository pattern and interfaces.
azamsharp
It has been my experience that L2S does not retrieve the entire object from the database, but gets it from cache. I have verified this by looking at the output via the context.Log method. When the object exists in cache, no SQL call was made to the DB.
Randy Minder
That is weird because I can see the query fired from L2S using SQL profiler for the select statement. I inserted the object first and then retrieved it using Id.
azamsharp