更改前获取实体 [英] get the entity before change

查看:68
本文介绍了更改前获取实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个实体:Product和StockItem。

插入产品时-我必须更新相关的StockItem。

删除产品时-我必须更新相关的StockItem也是如此。

I have two entities: Product and StockItem.
When I insert a product - I have to update the relevant StockItem.
When I delete a product - I have to update the relevant StockItem as well.

我的问题是在产品更新(修改)的情况下更新库存项目。为了更新相关的StockItem,我需要知道Product实体中名为Group的字段是否已更改。为此,我必须在实体的修改版本和实体的未修改版本之间进行比较。但是,每当我请求实体时,实体框架都会返回附加的实体(而不是数据库中的旧实体)。

My problem is updating the stock item in case of product update (modification). In order to update the relevant StockItem, I need to know if a field named Group in the Product entity has changed. To do so I have to compare between the modified version of the entity and the unmodified version of the entity. But whenever I ask for the entity - the entity framework returns the attached entity (and not the old one from the database).

我如何要求实体框架返回实体的旧版本/当前数据库版本(更改前)?

How can I ask the entity framework to return the old version / current db version of the entity (before change)?

推荐答案

您看到的是 ORM工具使用的身份映射模式。每个具有唯一实体密钥的实体只能被附加到上下文一次; =您将永远不会拥有两个具有相同实体密钥的实体版本两次加载到同一上下文。

What you see is result of identity map pattern used by ORM tools. Every entity with unique entity key can be attached to the context only once = you will never have two versions of the entity with the same entity key loaded twice to the same context.

默认情况下,如果您的查询返回具有相同实体键的记录,则EF始终返回已加载的实例。可以更改此行为,但是仍然只有该实体的单个实例。

By default EF always returns already loaded instance if your query returns record with the same entity key. This behaviour can be changed but still you will have only single instance of the entity.

您是否从EF使用与要使用的上下文实例相同的上下文实例加载了该实体为了省钱?如果是,则您已经具有旧值。使用:

Did you load the entity from EF with the same context instance as you are going to use for saving? If yes you already have old values. Use:

ObjectStateEntry entry = objectContext.ObjectStateManager.GetObjectStateEntry(yourEntity);
int someIntProperty = (int)entry.OriginalValues["SomeIntProperty"];

如果您未从同一上下文加载实体,您仍然可以使用此方法,但在此之前,您可以必须强制EF重新加载原始值:

If you didn't load entity from the same context you can still use this approach but before that you must force EF to reload original values:

objectContext.YourEntitySet.MergeOption = MergeOption.PreserveChanges;
YourEntity entity = objectContext.YourEntitySet.Single(e => e.Id == entityId);

现在输入的 OriginalValues 集合为

另一种解决方案是简单地使用两种不同的上下文-一种用于当前实体状态,一种用于旧实体状态。

Another solution is simply using two different contexts - one for current entity state and one for old entity state.

这篇关于更改前获取实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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