LINQ to SQL DataContext Caching

2020-07-22 10:36发布

问题:

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:

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.



回答2:

in my case work only with 4 bindings:

DATACONTEXT.GetType().InvokeMember(
    "ClearCache",
    BindingFlags.Instance |
    BindingFlags.Public |
    BindingFlags.NonPublic |
    BindingFlags.InvokeMethod,
    null, DATACONTEXT, null);


回答3:

There is one big caveat to manually calling 'ClearCache' - it is that you're doing exactly that! So - if you had any prior database operations (pending), you just flushed them. You have to be very careful that you haven't walked on other "On Submit" changes. I learned this the hard way - so I had to add a few more 'SubmitChanges' statements into my code - as a direct result of implementing ClearCache after some stored procedure executions (bulk deletes).



标签: linq-to-sql