Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetModifiedProperties not working for EF4.1 DbContext

With an 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

With a 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

I would like to migrate to using DbContext but I have code that is dependent on this feature. Is this a known bug? Can anyone suggest an alternative approach? Thanks.

like image 784
johndsamuels Avatar asked Feb 18 '23 05:02

johndsamuels


1 Answers

Ok, this seems to do the trick:

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

More useful information here: http://msdn.microsoft.com/en-US/data/jj592677

like image 124
johndsamuels Avatar answered Apr 08 '23 22:04

johndsamuels