我正在使用EF更新数据库表。
在连接模式下它是一个简单的场景。
我得到了我要更新的行
var order = from o in Orders
where o.ID = 1
select o;
然后我将记录更新为:
order.FirstName = "First";
order.LastName = "Last";
context.SaveChanges();
工作正常。 EF检查字段是否已更改,并仅在其为新值时更新字段。我在我的SQL服务器上启用了CDC,以检查如果值没有改变,EF不会重写到数据库。
现在我想把这个检查放在我的代码中以获得额外的逻辑,即我希望EF告诉我何时更新记录,何时不记录(因为值没有改变)。 任何人都可以告诉我们是否有办法?
我不想手动检查每个字段,因为我有很多要比较的字段。
由于
答案 0 :(得分:7)
如果有人对此感兴趣,那就是我所做的。我创建了以下方法来检查在保存更改之前是否有任何字段已更改。
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;
}
答案 1 :(得分:3)
当我寻找类似的东西(如果不是一样的东西)时,我遇到了这个问题/答案。我最终使用了这种方法,对我来说似乎很不错。
var order = from o in context.Orders
where o.ID = 1
select o;
order.FirstName = "First";
order.LastName = "Last";
if (context.Entry(order).State != EntityState.Unchanged)
{
// order has changed ...
}
因此发布对我有用的内容,以防其他人来这里寻找类似的东西。