代码改变世界

解决EF 4.0 中数据缓存机制

2014-04-12 00:11  ARMdong  阅读(1181)  评论(1编辑  收藏  举报

EF4.0默认开启缓存机制,如果想要禁用缓存机制的话,则须加上一句话:_db.CreateObjectSet().MergeOption = MergeOption.OverwriteChanges;

 public IQueryable<T> LoadEntities(Func<T, bool> whereLambda)
        {
            try
            {
                var set = _db.CreateObjectSet<T>();
                set.MergeOption = MergeOption.OverwriteChanges;
                var entities = set.Where<T>(whereLambda).AsQueryable();

                //var entities = _db.CreateObjectSet<T>().Where<T>(whereLambda).AsQueryable();

                return entities;
            }
            catch (Exception ex)
            {
                Logger.Error("LoadEntities Error!", ex);
                throw new Exception("LoadEntities Fail", ex);
            }
        }

这样,每次查询的时候都会去数据库查询最新的数据!