如何获取实体的旧值?
遵循示例..
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); }
答案 0 :(得分:0)
试试这个:
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);
}
或者这个:
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();
}
答案 1 :(得分:0)
我找到了一种使用反射将DbDataRecord转换为实体类型的方法......
其中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; } }