問題
ユーザーが編集したときに変更されたモデルの属性を保存したいと考えています。これが私がやりたいことです...
- 編集されたビュー モデルを取得する
- ドメイン モデルを取得し、更新された値をマップ バックします
- リポジトリで update メソッドを呼び出す
- 「古い」ドメイン モデルを取得し、フィールドの値を比較する
- 変更された値 (JSON 内) をテーブルに格納する
ただし、ステップ番号 4 で問題が発生しています。Entity Framework は、古い値を持つモデルを取得するためにデータベースに再度アクセスしたくないようです。私が持っているのと同じエンティティを返すだけです。
試みられた解決策
Find()
メソッドとメソッドを使用してみましたSingleOrDefault()
が、現在持っているモデルを返すだけです。
サンプルコード
private string ArchiveChanges(T updatedEntity)
{
//Here is the problem!
//oldEntity is the same as updatedEntity
T oldEntity = DbSet.SingleOrDefault(x => x.ID == updatedEntity.ID);
Dictionary<string, object> changed = new Dictionary<string, object>();
foreach (var propertyInfo in typeof(T).GetProperties())
{
var property = typeof(T).GetProperty(propertyInfo.Name);
//Get the old value and the new value from the models
var newValue = property.GetValue(updatedEntity, null);
var oldValue = property.GetValue(oldEntity, null);
//Check to see if the values are equal
if (!object.Equals(newValue, oldValue))
{
//Values have changed ... log it
changed.Add(propertyInfo.Name, newValue);
}
}
var ser = new System.Web.Script.Serialization.JavaScriptSerializer();
return ser.Serialize(changed);
}
public override void Update(T entityToUpdate)
{
//Do something with this
string json = ArchiveChanges(entityToUpdate);
entityToUpdate.AuditInfo.Updated = DateTime.Now;
entityToUpdate.AuditInfo.UpdatedBy = Thread.CurrentPrincipal.Identity.Name;
base.Update(entityToUpdate);
}