问题描述
我是实体框架的新手。在我的应用程序中,我首先创建了一个实体,并将其保存在数据库中。接下来,我对内存中的实体进行了一些更改,但是在将当前更改保存到数据库之前,我想将这些值与之前在数据库中保存的值进行比较。
I am very new to Entity Framework. In my application, I have first created an entity and got it saved in the database. Next, I have made some changes to the in-memory entity but before I saving the current changes to the database, I want to compare the values with what I have saved previously in the database.
当我尝试从数据库中加载实体时,EF依次返回当前在内存中的实体。
When I am trying to load the entity from the database, EF in turn returns the entity which is currently in memory.
我有兴趣知道,如何从数据库中获取实体,并将其与当前的内存中已修改实体分开?
I am interested in knowing, how can I fetch an entity from database and also keep it separate from the current in-memory modified entity?
示例代码
// new entity being created
Person p1 = GetPersonEntity();
p1.Age = 20;
Guid p1Id = _personRepository.AddOrUpdate(p1);
// An update but before saving I want to compare the new age with what was saved previously
p1.Age = 25;
Guid tempId = _personRepository.AddOrUpdate(p1);
// For comparison when I try to fetch entity from database,
// I am getting the current in memory modified entity
_personRepository.FindBy(x => x.Id == p1Id).FirstOrDefault(); // doesn't return values from database
返回值
谢谢
Thanks
推荐答案
如果对象仍连接到上下文(您尚未处理上下文),则无需从数据库中加载对象。
You don't need to load the object from the database if the object is still connected to the context (you haven't disposed of the context).
签出。该对象同时具有 OriginalValues
和 CurrentValues
属性。
Check out ObjectStateManager.GetObjectStateEntry. The object that returns is an ObjectStateEntry. That object has both OriginalValues
, and CurrentValues
properties.
DbContext会从对象最初加载时开始维护它的状态。这是EF在调用 context.SaveChanges()
时用于确定是否需要写入数据库的方法。如果您要查找的是,则只能访问已更改的属性。这些可以在 ObjectStateEntry
的 GetModifiedProperties()
方法中找到。
The DbContext maintains the state of the object from when it was originally loaded. This is what EF uses to determine if it needs to write to the database when you call context.SaveChanges()
. You can access just the properties that have changed, if that's what you're looking for. Those are found in the GetModifiedProperties()
method on the ObjectStateEntry
.
这篇关于实体框架和维护实体的两个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!