GetModifiedProperties不适用于EF4.1 DbContext

时间:2013-03-12 08:43:59

标签: entity-framework

使用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,但我的代码依赖于此功能。这是一个已知的错误?任何人都可以提出替代方法吗?感谢。

1 个答案:

答案 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

更多有用信息:http://msdn.microsoft.com/en-US/data/jj592677