2011-10-26 10 views
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); 

    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

はこのお試しください例を次の

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(); 
} 
+0

ありがとう、これはうまくいきましたが、別の疑問があります。 このDbDataRecordからどのようにエンティティを取得できますか? – Hemerson

0

を私はリフレクションを使用してエンティティタイプにDbDataRecordを変換する1つの方法を見つけ.. 。

ここでは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; 
     } 
    }