[英]Implementing Audit trail c#
i implemented an audit log for every action made in the server (added, modified and delete). 我为服务器中的每个操作实现了一个审核日志(添加,修改和删除)。 The problem occurs in the modified, because i audit every property which was modified, but some properties i don`t want to audit.
问题出现在修改过的,因为我审核了每个被修改的属性,但是我不想审计一些属性。 Ex: Timestamp, or others.
例如:时间戳或其他。 This is what i did, and works fine: 1) I made another SaveChanges() method into DBContext 2)
这就是我做的,并且工作正常:1)我在DBContext中创建了另一个SaveChanges()方法2)
if (dbEntity.State == EntityState.Modified)
{
foreach (string propertyName in dbEntity.OriginalValues.PropertyNames)
{
if (!Equals(dbEntity.OriginalValues.GetValue<object>(propertyName), dbEntity.CurrentValues.GetValue<object>(propertyName)))
{
var log = new AuditLogDetailEntity()
{
Timestamp = timestamp,
Type = "M", // Modified
EntityName = tableName1,
PrimaryKeyValue = Convert.ToInt32(dbEntity.CurrentValues.GetValue<object>(primaryKeyName)),
PropertyName = propertyName,
OldValue = dbEntity.OriginalValues.GetValue<object>(propertyName) == null ? null : dbEntity.OriginalValues.GetValue<object>(propertyName).ToString(),
NewValue = dbEntity.CurrentValues.GetValue<object>(propertyName) == null ? null : dbEntity.CurrentValues.GetValue<object>(propertyName).ToString()
};
changesCollection.Add(log);
}
}
}`
This is an extract code, not all the funcion. 这是一个提取代码,而不是所有的功能。 I could make a validation inside, asking for that fields I don`t want to audit, but, Is there a more thorough way of doing it?
我可以在里面进行验证,询问我不想审核的字段,但是,有没有更彻底的方法呢? Maybe adding some dataannotations in the classes, or something else.. thanks.
也许在类中添加一些数据注释,或其他东西..谢谢。
您可以使用[System.ComponentModel.DataAnnotations.Schema.NotMapped]属性。
You could create a custom attribute 您可以创建自定义属性
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class UnMappedAttribute : Attribute
{
}
And then check if each property has it 然后检查每个属性是否都有
foreach (string propertyName in dbEntity.OriginalValues.PropertyNames)
{
if(!dbEntity.Entity.GetType().GetCustomAttributes(typeof(UnMappedAttribute), true).Any())
{
continue;
}
if (!Equals(dbEntity.OriginalValues.GetValue<object>(propertyName), dbEntity.CurrentValues.GetValue<object>(propertyName)))
{
//.....
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.