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