LINQ to SQL DataContext缓存 [英] LINQ to SQL DataContext Caching

查看:57
本文介绍了LINQ to SQL DataContext缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Linq to SQL作为我的DAL层,在单元测试期间,我发现我的对象不是从数据库返回的,而是从DataContext缓存中返回的.

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.

无论如何,我实现了一个ClearCache方法,该方法将清除缓存.但是我只清除单元测试中的缓存,而不清除API代码中的缓存.

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.

您怎么看?

更新:

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);
        }

推荐答案

您是正确的,L2S将在可能时从缓存中返回项目.我通过艰辛的方式了解了这一点.处理此问题的一种干净方法是在每次插入和更新操作之后执行一个context.RefreshRow.这将刷新缓存并确保缓存是最新的.

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.

这篇关于LINQ to SQL DataContext缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆