Reputation: 18521
Lets say I have the following objects
public class Car{
public int id;
public string name;
public string color;
publid DateTime LastUpdateDate;
}
public class CarPart{
public int id;
public string name;
public string color;
}
Whenever someone updates any field, I want the LastUpdateDate field to be updated.
My worst design is to write something like the following
public void setName(string name){
this.name=name;
this.LastUpdateDate = DateTime.now;
}
a. the classes are auto generated and I would have to maintain a partial.
b. too coupled.
notice: I am looking for something that will handle it for a field change in the object(Car) and its multivalue (CarPart) objects Thanks.
Upvotes: 1
Views: 1279
Reputation: 49095
Most people tend to override the Context's SaveChanges()
method for auditing.
First create an IAuditable
interface and apply it on all Entities you want to audit:
public interface IAuditable
{
public DateTime? LastUpdateDate { get; set; }
}
Then in your Context
:
public override int SaveChanges()
{
var entries = ChangeTracker.Entries()
.Where(e => e.State == EntityState.Modified);
foreach (var entry in entries)
{
var auditableEntity = entry.Entity as IAuditable;
if (auditableEntity != null)
auditableEntity.LastUpdateDate = DateTime.UtcNow;
}
return base.SaveChanges();
}
Also, take a look at
Upvotes: 2