[英]Auditing Entity Framework Actions
請保持溫柔,這是我的第一篇文章,非常抱歉,如果我第一次沒有正確使用術語。
在Entity Framework
我需要編寫一些審核代碼 。
我有一個上下文類,它繼承了具有數據庫的DbContext
。 每個實體的SetInitializer
和My DbSets
。
在執行審核的地方,我還具有對SaveChanges的覆蓋。
共有3個審核級別,分別為None , Basic和AllProperty ,每個實體都分配有不同的屬性,在這種情況下,我嘗試進行AllProperties審核。
這適用於EntityState.Modified
,其中我在foreach中使用GetModifiedProperties
為每個修改的屬性寫入新記錄
但是我很難對EntityState.Added
做同樣的EntityState.Added
,似乎沒有等效的GetNewProperties
可以循環通過。
case AuditType.AllProperties:
{
if (entry.State == EntityState.Modified)
{
foreach (var propertyName in entry.GetModifiedProperties()
.Where(propertyName => propertyName != "Id" && propertyName != "RowVersion"))
{
var original = entry.OriginalValues;
var oldValue = original.GetValue(original.GetOrdinal(propertyName)).ToString();
var current = entry.CurrentValues;
var newValue = current.GetValue(current.GetOrdinal(propertyName)).ToString();
//if (oldValue != newValue) // probably not necessary
//{
AuditTrails.Add(new AuditTrail
{
DomainId = domainId,
Controller = "",
Action = "",
EntityType = entry.Entity.GetType().Name,
EntityId = entityId,
Property = propertyName,
Before = oldValue,
After = newValue
});
}
}
else
{
AuditTrails.Add(new AuditTrail
{
DomainId = domainId,
Controller = "",
Action = "",
EntityType = entry.Entity.GetType().Name,
EntityId = entityId,
EntityValue = entry.Entity.ToString(),
Property = "",
Before = "",
After = entry.State.ToString()
});
}
有人可以幫忙嗎?
每當調用entry.OriginalValues
,您都可以訪問PropertyNames
屬性,該屬性將為您提供所有屬性的列表。 由於這是一個新條目,因此無論如何它們都是新的。
以下內容目前適用於我
if (entry.State == EntityState.Added)
{
for (var i = 0; i < entry.CurrentValues.FieldCount; i++)
{
var propertyName = entry.CurrentValues.DataRecordInfo.FieldMetadata[i].FieldType.Name;
if (propertyName == "Id") continue;
if (propertyName == "RowVersion") continue;
AuditTrails.Add(new AuditTrail
{
DomainId = domainId,
Controller = "",
Action = entry.State.ToString(),
EntityType = entityType,
EntityId = entityId,
EntityValue = "", //entityValue,
Property = propertyName,
Before = "",
After = entry.CurrentValues[i].ToString(),
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.