Be gentle, Its my first post so sorry if I don't get the terminology right first time.
In Entity Framework
I need to write some auditing code.
I have a context class which inherits DbContext
which has my Database.
SetInitializer
and My DbSets
for each entity.
I also have an override of SaveChanges where I am doing the auditing.
There are 3 levels of auditing, None, Basic and AllProperties and each Entity has a different property assigned to it, in this case I am trying to do an AllProperties audit.
This works for EntityState.Modified
where I am using GetModifiedProperties
in a foreach to write a new record for each property amended
But I am having trouble doing the same for EntityState.Added
, there doesn't seem to be an equivalent GetNewProperties
that I can loop through.
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()
});
}
Can anyone help?