Bick
Bick

Reputation: 18521

EF - Automatic update of a field when another is updating (Last Update Date)

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.

  1. Is there a recommended framework/design pattern I can use to solve this?
  2. Does Entityframework has a feature that handle this requirement.

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

Answers (1)

haim770
haim770

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

  1. AuditDbContext
  2. Entity Framework 6 Interception (new feature).

Upvotes: 2

Related Questions