0

Every table in my database has a CreatedDate and LastModifiedDate column. Is there a way in EF to automatically set those columns during INSERT and UPDATE operations respectively?

I am trying to avoid having people try to remember to manually set them in application code, as that's error prone. (And no, I don't want to put triggers on every table.)

Jonathan Allen
  • 68,373
  • 70
  • 259
  • 447

2 Answers2

1

If you use Generic Repository pattern , there is a simple solution . You can use below code for Add entity

 public T Add(T entity)
    {
        typeof(T).GetField("CreatedDate").SetValue(entity, DateTime.Now);
        return this.DbSet.Add(entity);
    }

and update entity like below

  public virtual void Edit(T entity)
    {
        typeof(T).GetField("LastModifiedDate").SetValue(entity, DateTime.Now);
        this.Context.Edit(entity);
    }
1

If you have CreatedDate and LastModifiedDate in every table, then probably you have some abstract BaseModel which has these two properties. Then you can override SaveChanges method inside your context and set these properties:

private void SetOperationDates()
{
    // Get added entries
    IEnumerable<ObjectStateEntry> addedEntryCollection = Context
        .ObjectContext
        .ObjectStateManager
        .GetObjectStateEntries(EntityState.Added)
        .Where(m => m != null && m.Entity != null);

    // Get modified entries
    IEnumerable<ObjectStateEntry> modifiedEntryCollection = Context
        .ObjectContext
        .ObjectStateManager
        .GetObjectStateEntries(EntityState.Modified)
        .Where(m => m != null && m.Entity != null);

    // Set CreatedDate of added entries
    foreach (ObjectStateEntry entry in addedEntryCollection)
    {                
        BaseModel addedEntity = entry.Entity as BaseModel;
        if (addedEntity != null)
            addedEntity.CreatedDate = DateTime.Now;
    }

    // Set LastModifiedDate of modified entries
    foreach (ObjectStateEntry entry in modifiedEntryCollection)
    {
        BaseModel modifiedEntity = entry.Entity as BaseModel;
        if (modifiedEntity != null)
            modifiedEntity.LastModifiedDate = DateTime.Now;
    }
}

public override int SaveChanges()
{
    SetOperationDates();

    return SaveChanges();
}

Note: You can also add overload version of SaveChanges method whith bool parameter in case you do not want to call SetOperationDates.

Adil Mammadov
  • 8,476
  • 4
  • 31
  • 59