0

I was wondering if there is a better way to update an entity property from inside of an overridden SaveChanges() method. I am currently using straight SQL.

Here is the snippet from SaveChanges()

public override SaveChanges(){                
        [...]
        if (updateId > 0)
        {
            string q = @"UPDATE NewClub SET 
                 LastActivityDate='" + DateTime.Now + "' WHERE Id=" + updateId;

            using (var context = new ReportingContext())
            {
                //ToDo: exception handling
                var result = context.Database.ExecuteSqlCommand(q);
            }
        }
    try
    {
        saveSuccess = base.SaveChanges() > 0;
    }
    catch (Exception e)
    {
        string ex = e.ToString();
    }
    return saveSuccess ? 1 : 0;
}
Christian Phillips
  • 18,399
  • 8
  • 53
  • 82
Slinky
  • 5,662
  • 14
  • 76
  • 130
  • You could use a trigger (in the database itself) for this specific example at least. – Bill May 20 '14 at 18:33
  • 2
    @Bill Thanks. I am trying to avoid triggers because people around here forget they are doing stuff with them and then nobody knows how certain pieces of data are changing. – Slinky May 20 '14 at 18:44
  • Haha! Good call. Heck, maybe I should start avoiding them for the same reason. – Bill May 20 '14 at 18:46
  • You could look into using Interceptors in EF6. – Dismissile May 20 '14 at 19:05

1 Answers1

0

I am using the trick described at the start of this video for our latest app, and have had great success so far.

public int SaveChanges(IPrincipal user)
    {
        foreach (var dbEntityEntry in this.ChangeTracker.Entries()
            .Where(e => e.Entity is BaseEntity &&
            ((e.State == EntityState.Modified) || (e.State == EntityState.Added))))
        {
            ((BaseEntity) dbEntityEntry.Entity).ModificationBy = user.Identity.Name;
            ((BaseEntity)dbEntityEntry.Entity).ModificationDate = TimeProvider.Current.Now;

        }
        return base.SaveChanges();
    }

We only expose this Save method through the context interface.

public interface IMyContext
{
    int SaveChanges(IPrincipal user);
}
Tim Sneed
  • 490
  • 3
  • 10