use*_*065 9 c# entity-framework
我使用EF5,并且在我将此实体的唯一更改的PropertyValue设置回原始值之后,不知道为什么实体具有"已修改"状态.
using (TestDbContext context = new TestDbContext())
{
string name = context.Person.First().Name;
// count is 0
int count = context.ChangeTracker.Entries().Count(e => e.State == EntityState.Modified);
// Change Value
context.Person.First().Name = "Test";
// count is 1
count = context.ChangeTracker.Entries().Count(e => e.State == EntityState.Modified);
// Revert Value
context.Person.First().Name = name;
context.ChangeTracker.DetectChanges();
// count is 1
count = context.ChangeTracker.Entries().Count(e => e.State == EntityState.Modified);
}
Run Code Online (Sandbox Code Playgroud)
为什么?:(
小智 16
因为实体框架仅跟踪数据是否被修改,而不是跟它的原始内容不同.
当实体不变时,我们使用一个漂亮的方法将状态重置为未修改:
public static void CheckIfModified(EntityObject entity, ObjectContext context)
{
if (entity.EntityState == EntityState.Modified)
{
ObjectStateEntry state = context.ObjectStateManager.GetObjectStateEntry(entity);
DbDataRecord orig = state.OriginalValues;
CurrentValueRecord curr = state.CurrentValues;
bool changed = false;
for (int i = 0; i < orig.FieldCount && !changed; ++i)
{
object origValue = orig.GetValue(i);
object curValue = curr.GetValue(i);
if (!origValue.Equals(curValue) && (!(origValue is byte[]) || !((byte[])origValue).SequenceEqual((byte[])curValue)))
{
changed = true;
}
}
if (!changed)
{
state.ChangeState(EntityState.Unchanged);
}
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,此方法适用于EF 4.0,而不适用于具有DbContext的较新版本.但是重写它以使用EF 4.1+没有问题,我已经自己做了,但我现在找不到代码.
谢谢提示:)
这是我的 EF5 (DbContext) 解决方案。我为从 ChangeTracker.Entries() 获得的每个 DbEnityEntry 调用此方法
private void CheckIfDifferent(DbEntityEntry entry)
{
if (entry.State != EntityState.Modified)
return;
if (entry.OriginalValues.PropertyNames.Any(propertyName => !entry.OriginalValues[propertyName].Equals(entry.CurrentValues[propertyName])))
return;
(this.dbContext as IObjectContextAdapter).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity).ChangeState(EntityState.Unchanged);
}
Run Code Online (Sandbox Code Playgroud)