使用ObjectContext:
var objContext = new ObjContextEntities();
var accountType = objContext.AccountTypes.FirstOrDefault(x => x.Id == 0);
accountType.Name = "ABC";
var stateEntry = objContext.ObjectStateManager.GetObjectStateEntry(accountType);
Console.WriteLine(stateEntry.GetModifiedProperties().Count()); //--------> Outputs 1 as expected
使用DbContext:
var dbContext = new DbContextEntities();
var accountType = dbContext.DBAccountTypes.FirstOrDefault(x => x.Id == 0);
accountType.Name = "XYZ";
var dbObjContext = ((IObjectContextAdapter)dbContext).ObjectContext;
var stateEntry = dbObjContext.ObjectStateManager.GetObjectStateEntry(accountType);
Console.WriteLine(stateEntry.GetModifiedProperties().Count()); //--------> Outputs 0
我想迁移到使用DbContext,但我的代码依赖于此功能。这是一个已知的错误?任何人都可以提出替代方法吗?感谢。
答案 0 :(得分:8)
好的,这似乎可以解决问题:
var dbContext = new DbContextEntities();
var accountType = dbContext.DBAccountTypes.FirstOrDefault(x => x.Id == 0);
accountType.Name = "XYZ";
var entry = dbContext.Entry(accountType);
var modifiedProperties = entry.CurrentValues.PropertyNames.Where(propertyName => entry.Property(propertyName).IsModified).ToList();
Console.WriteLine(modifiedProperties.Count()); //--------> Outputs 1