实体框架更新检查记录是否已更改 [英] Entity Framework Update check if the record has changed
问题描述
我正在使用EF更新数据库表。
它是连接模式下的简单场景。
我得到我要更新的行
var order = from o在Orders
中,其中o.ID = 1
选择o;
然后我将记录更新为:
order.FirstName =First;
order.LastName =Last;
context.SaveChanges();
它工作正常。 EF检查字段是否已更改,只有在新字段更新该字段。我已经启用CDC在我的SQL服务器上检查,如果该值没有改变,EF不会重写到数据库。
现在我想把这个签入我的代码对于额外的逻辑,即我希望EF告诉我什么时候更新记录,何时不是(因为值没有改变)。
任何人都可以告诉你有没有办法?
我不想手动检查每个字段,因为我有很多字段进行比较。 p>
感谢
如果有人对这里感兴趣,我创建了以下方法来检查在保存更改之前是否有任何字段已更改。
私人字典< Type,bool> IsEntityModified()
{
字典< Type,bool> entity = new Dictionary< Type,bool>();
var items = _bentities.ObjectStateManager.GetObjectStateEntries(EntityState.Modified);
foreach(项目中的ObjectStateEntry条目)
{
foreach(entry.GetModifiedProperties()中的string propName)
{
string oldsetterValue,newsetterValue = null;
//获取原始值
oldsetterValue = entry.OriginalValues [propName] .ToString();
//获取新值
newsetterValue = entry.CurrentValues [propName] .ToString();
if(oldsetterValue!= newsetterValue)
{
entity.Add(entry.Entity.GetType(),true);
}
}
}
返回实体;
}
I am updating a database table using EF.
Its a simple scenario in connected mode.
I get the row I want to update
var order = from o in Orders
where o.ID = 1
select o;
I then update the record as:
order.FirstName = "First";
order.LastName = "Last";
context.SaveChanges();
It works fine. EF checks if the field has changed and only updates the field if its a new value. I have enabled CDC on my SQL server to check that EF does not rewrite to the database if the value has not changed.
Now I want to put this check in my code for additional logic i.e. I want EF to tell me when the record was updated, and when it was not (because the value has not changed). Can anyone please tell if there is a way?
I do not want to manually check each field as I have a lot of fields to compare.
Thanks
If anybody is interested here is what I did. I created the following method to check if any field has changed before saving changes.
private Dictionary<Type, bool> IsEntityModified()
{
Dictionary<Type, bool> entity = new Dictionary<Type, bool>();
var items = _bentities.ObjectStateManager.GetObjectStateEntries(EntityState.Modified);
foreach (ObjectStateEntry entry in items)
{
foreach (string propName in entry.GetModifiedProperties())
{
string oldsetterValue, newsetterValue = null;
//Get orginal value
oldsetterValue = entry.OriginalValues[propName].ToString();
//Get new value
newsetterValue = entry.CurrentValues[propName].ToString();
if (oldsetterValue != newsetterValue)
{
entity.Add(entry.Entity.GetType(), true);
}
}
}
return entity;
}
这篇关于实体框架更新检查记录是否已更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!