实体框架和缓存 - 更改正在追溯到缓存 [英] Entity Framework and caching - Changes are tracking back to cache

查看:155
本文介绍了实体框架和缓存 - 更改正在追溯到缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些数据被从Entity模型中拉入。这包含项目的属性,假设汽车零件具有最大速度,重量和尺寸。由于有很多零件和基础属性永远不会改变,我已经缓存了所有的记录。



根据这些零件的使用情况,这些属性可能现在要更改,所以我设置一辆新车,将值从缓存的项目引擎复制到新的汽车对象,然后添加TurboCharger,这提高了引擎的最大速度,重量和大小。



我遇到的问题是,实体模型似乎仍然将缓存的数据追溯到 。所以当本地方法增加权重时,会增加所有用户的权重。我尝试将MergeOption.NoTracking添加到我的上下文中,因为这应该是删除所有的实体跟踪,但它似乎仍然被追踪。如果我关闭缓存,它可以正常工作,因为它每次从数据库中提取新值。



如果我要从我的实体模型复制记录,是否一种方法可以说复制对象,但将其视为没有来自实体的历史的标准对象,这样一旦我的车有一个项目的属性,它只是一个扁平的对象?



Cheers!

解决方案

我完全不知道MergeOption.NoTracking是什么这样做,但您可以做的另一种做法是将.AsNoTracking()从数据库添加到查询中。这一定会返回一个分离的对象。
看看这里有关AsNoTracking用法的一些细节: http://blog.staticvoid.co.nz/2012/04/entity-framework-and-asnotracking.html



另一件事是要确保在列入缓存之前枚举您的集合,以确保您不可执行的行为,即使用.ToArray()。



另一个选项是手动将对象从上下文中分离(使用Detach(T entity))。


I have some data being pulled in from an Entity model. This contains attributes of items, let's say car parts with max-speed, weight and size. Since there are a lot of parts and the base attributes never change, I've cached all the records.

Depending on the car these parts are used in, these attributes might now be changed, so I setup a new car, copy the values from the cached item "Engine" to the new car object and then add "TurboCharger", which boosts max speed, weight and size of the Engine.

The problem I'm running into is that it seems that the Entity model is still tracking the context back to the cached data. So when weight is increased by the local method, it increases it for all users. I tried adding "MergeOption.NoTracking" to my context as this is supposed to remove all entity tracking, but it still seems to be tracking back. If I turn off the cache, it works fine as it pulls fresh values from the database each time.

If I want to copy a record from my entity model, is there a way I can say "Copy the object but treat it as a standard object with no history of coming from entity" so that once my car has the attributes from an item, it is just a flattened object?

Cheers!

解决方案

Im not too sure about MergeOption.NoTracking on the whole context and exactly what that does but what you can do as an alternative is to add .AsNoTracking() into your query from the database. This will definitely return a detached object. Take a look here for some details on AsNoTracking usage : http://blog.staticvoid.co.nz/2012/04/entity-framework-and-asnotracking.html.

The other thing is to make sure you enumerate your collection before you insert to the cache to ensure that you arent acting within the queriable, ie use .ToArray().

The other option is to manually detach the object from the context (using Detach(T entity)).

这篇关于实体框架和缓存 - 更改正在追溯到缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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