Я использую AuditTrail для регистрации, но у меня проблема. Я попробовал этот метод;
http://kamoga.net/audit-trail-and-entity-change-tracking-using-entity-framework-dbcontext/
Но я не удаляю записи для операций удаления. У меня есть столбец IsDeleted и я установил для этого столбца значение true.
Если я использую EntityState.Modified в своем ActionResult, мой столбец «Действие» установит «U», но я хочу установить «D» в базе данных.
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
dbContext = new dbContext();
Gallery gallery = dbContext.Gallery.Find(id);
gallery.IsDeleted = true;
dbContext.Entry(gallery).State = System.Data.Entity.EntityState.Modified;
dbContext.SaveChanges();
}
My Enum;
public enum AuditActions
{
I,
U,
A
}
AuditTrail.cs;
public class AuditTrail
{
public int Id { get; set; }
public string TableName { get; set; }
public string UserName { get; set; }
public string Actions { get; set; }
public string OldData { get; set; }
public string NewData { get; set; }
public string ChangedColums { get; set; }
public string TableIdValue { get; set; }
}
AuditFactoryTrail.cs;
public AuditTrail GetAudit(DbEntityEntry entry)
{
AuditTrail audit = new AuditTrail();
audit.UserName = "Current User"; //You can pass the current user as a parameter
audit.TableName = GetTableName(entry);
audit.TableIdValue = GetKeyValue(entry);
//entry is Added
if (entry.State == EntityState.Added)
{
var newValues = new StringBuilder();
SetAddedProperties(entry, newValues);
audit.NewData = newValues.ToString();
audit.Actions = AuditActions.I.ToString();
}
//entry in deleted
else if (entry.State == EntityState.Deleted)
{
var oldValues = new StringBuilder();
SetDeletedProperties(entry, oldValues);
audit.OldData = oldValues.ToString();
audit.Actions = AuditActions.D.ToString();
}
//entry is modified
else if (entry.State == EntityState.Modified)
{
var oldValues = new StringBuilder();
var newValues = new StringBuilder();
SetModifiedProperties(entry, oldValues, newValues);
audit.OldData = oldValues.ToString();
audit.NewData = newValues.ToString();
audit.Actions = AuditActions.U.ToString();
var modifiedProperties = entry.CurrentValues.PropertyNames.Where(propertyName => entry.Property(propertyName).IsModified).ToList();
var properties = string.Join("||", modifiedProperties.ToList());
audit.ChangedColums = properties;
}
return audit;
}
private void SetAddedProperties(DbEntityEntry entry, StringBuilder newData)
{
foreach (var propertyName in entry.CurrentValues.PropertyNames)
{
var newVal = entry.CurrentValues[propertyName];
if (newVal != null)
{
newData.AppendFormat("{0}={1} || ", propertyName, newVal);
}
}
if (newData.Length > 0)
newData = newData.Remove(newData.Length - 3, 3);
}
private void SetDeletedProperties(DbEntityEntry entry, StringBuilder oldData)
{
DbPropertyValues dbValues = entry.GetDatabaseValues();
foreach (var propertyName in dbValues.PropertyNames)
{
var oldVal = dbValues[propertyName];
if (oldVal != null)
{
oldData.AppendFormat("{0}={1} || ", propertyName, oldVal);
}
}
if (oldData.Length > 0)
oldData = oldData.Remove(oldData.Length - 3, 3);
}
private void SetModifiedProperties(DbEntityEntry entry, StringBuilder oldData, StringBuilder newData)
{
DbPropertyValues dbValues = entry.GetDatabaseValues();
foreach (var propertyName in entry.OriginalValues.PropertyNames)
{
var oldVal = dbValues[propertyName];
var newVal = entry.CurrentValues[propertyName];
if (oldVal != null && newVal != null && !Equals(oldVal, newVal))
{
newData.AppendFormat("{0}={1} || ", propertyName, newVal);
oldData.AppendFormat("{0}={1} || ", propertyName, oldVal);
}
}
if (oldData.Length > 0)
oldData = oldData.Remove(oldData.Length - 3, 3);
if (newData.Length > 0)
newData = newData.Remove(newData.Length - 3, 3);
}
private string GetKeyValue(DbEntityEntry entry)
{
var objectStateEntry = ((IObjectContextAdapter)context).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity);
string id = "0";
if (objectStateEntry.EntityKey.EntityKeyValues != null)
id = objectStateEntry.EntityKey.EntityKeyValues[0].Value.ToString();
return id;
}
private string GetTableName(DbEntityEntry dbEntry)
{
TableAttribute tableAttr = dbEntry.Entity.GetType().GetCustomAttributes(typeof(TableAttribute), false).SingleOrDefault() as TableAttribute;
string tableName = tableAttr != null ? tableAttr.Name : dbEntry.Entity.GetType().Name;
return tableName;
}
private EntityObject CloneEntity(EntityObject obj)
{
DataContractSerializer dcSer = new DataContractSerializer(obj.GetType());
MemoryStream memoryStream = new MemoryStream();
dcSer.WriteObject(memoryStream, obj);
memoryStream.Position = 0;
EntityObject newObject = (EntityObject)dcSer.ReadObject(memoryStream);
return newObject;
}
}
DbContext.cs;
public override int SaveChanges()
{
var auditFactory = new AuditTrailFactory(this);
var entityList = ChangeTracker.Entries().Where(p =>
p.State == EntityState.Added ||
p.State == EntityState.Deleted ||
p.State == EntityState.Modified ||
!(p.Entity is AuditTrail) ||
p.Entity != null);
entityList.ToList().ForEach(entity =>
{
AuditTrail audit = auditFactory.GetAudit(entity);
AuditTrail.Add(audit);
});
return base.SaveChanges();
}