How do I get the old values of an entity?
How do I get the old values of an entity?
follows the example..
public void Update(User user) ValidateEntity(user, OperationType.Update); oldUser = (how do I get the old values (database) of the entity User?) Set.Attach(user); Context.ObjectStateManager.ChangeObjectState(user, EntityState.Modified); Context.SaveChanges(); OnUpdated(user, oldUser); }
Try this:
public void Update(User user)
ValidateEntity(user, OperationType.Update);
var oldUser = Set.Single(u => u.Id == user.Id);
Context.Detach(oldUser);
Set.Attach(user);
Context.ObjectStateManager.ChangeObjectState(user, EntityState.Modified);
Context.SaveChanges();
OnUpdated(user, oldUser);
}
Or this:
public void Update(User user)
{
ValidateEntity(user, OperationType.Update);
var oldUser = Set.Single(u => u.Id == user.Id);
Set.ApplyCurrentValues(user);
Context.SaveChanges(SaveOptions.DetectChangesBeforeSave);
OnUpdated(user, Context.ObjectStateManager.GetOjectStateEntry(user).OriginalValues);
Context.AcceptAllChanges();
}
I found one way of convert DbDataRecord to entity type using reflection...
where http://www.instanceofanobject.com/2011/01/ef4-dbdatarecord-convertto.html
public static class AnonymousTypeConversion { /// /// Converts a single DbDataRwcord object into something else. /// The destination type must have a default constructor. /// /// /// /// public static T ConvertTo(this DbDataRecord record) { T item = Activator.CreateInstance(); for (int f = 0; f /// Converts a list of DbDataRecord to a list of something else. /// /// /// /// public static List ConvertTo(this List list) { List result = (List)Activator.CreateInstance>(); list.ForEach(rec => { result.Add(rec.ConvertTo()); }); return result; } }链接地址: http://www.djcxy.com/p/33590.html
上一篇: 实体框架,更新相关对象的问题
下一篇: 我如何获得实体的旧价值?