これは重複していると確信していますが、SOまたはGoogleで探しているものを正確に見つけることができないようです。
Entity Framework 5 (最初にデータベース) を介して特定のエンティティの変更を追跡するために、データ監査を設定しています。フィールド/列レベルで変更を追跡する単一のログ テーブルを使用しています。テーブル名 (エンティティ名ではない) と列名 (エンティティ フィールド名ではない) を追跡したい。
MetaDataWorkspace を使用して多くのことを試しましたが、探している正確な結果が得られないようです。どれも実りのないものだったので、メタデータ コードは含めません。私が抱えていた問題の 1 つは、私のエンティティが実際には実行時に動的プロキシであることに注意してください。
これが私の現在のコードです:
IEnumerable<DbEntityEntry> entities =
context.ChangeTracker.Entries()
.Where(
e =>
e.State == EntityState.Added || e.State == EntityState.Modified);
bool auditingRequired = false;
var auditEntities = new List<AuditEntity>();
foreach (DbEntityEntry entity in entities)
{
//IFullyAudited is a marker for the entities I want to track
if (!(entity.Entity is IFullyAudited)) continue;
auditingRequired = true;
//note that entity.Entity is actually a dynamic proxy here
string tableName = ""; //how can I get the actual table name (not the entity name)
//there would be different logic for adds and edits--this just covers edits
foreach (string propertyName in entity.OriginalValues.PropertyNames)
{
string columnName = ""; //how can I get the actual column name?
var currentValue = entity.CurrentValues.GetValue<object>(propertyName);
var originalValue = entity.OriginalValues.GetValue<object>(propertyName);
if (!Equals(currentValue, originalValue))
{
//just a fake/POCO, not a real EF Entity until I figure this out
auditEntities.Add(new AuditEntity
{
//save PK here as well
ColumnName = columnName,
TableName = tableName,
NewValue = currentValue.ToString(),
OldValue = originalValue.ToString()
});
}
}
}
if (auditingRequired)
{
//here I will add the audit entity to the context
}