Ken Pespisa
Ken Pespisa

Reputation: 22264

Entity Framework 4.1 (Code First) audit column

I'm using Entity Framework 4.1 with a Code-First approach on an ASP.NET MVC site

Say I have an entity named Profile that keeps track of a user's favorite book, and I want to track when the user updates their favorite book.

UPDATED:

Using the class below as an example, I want to set the FavoriteBookLastUpdated property to the current date whenever the value of the FavoriteBook property changes.

public class Profile
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string FavoriteBook { get; set; }
    public DateTime? FavoriteBookLastUpdated { get; set; }
}

Right now I just update that field, if appropriate, in the controller's Edit action before calling the DBContext's SaveChanges() method.

Is there a way I can put that logic in my model somehow? I'd prefer not to use triggers on the database side.

Upvotes: 0

Views: 1133

Answers (2)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364319

If you don't like the @Per Hornshøj-Schierbeck's answer which I think is correct one you can try to use EF for that:

public override int SaveChanges() 
{
    foreach (var entry in ChangeTracker.Entries<Profile>())
    {
        if (entry.OriginalValues == null || // I'm not sure what value this have if entity is not loaded
            entry.Entity.FavoritBook != entry.OriginalValues["FavoriteBook"].ToString())
        {
            entry.Entity.FavoriteBookLastUpdated = DateTime.Now;
        }
    }

    return base.SaveChanges();
}

Upvotes: 3

EDIT: I read your comment and new example :)

Could you not have your Favorite book property be an actual property that also sets LastModified? I'm not sure if EF4 will accept that, but then you could make a public property for changing the FavoriteBook and a special one for EF4 only. You might need to make the special property 'InternalsVisibleTo'

http://msdn.microsoft.com/en-us/library/0tke9fxk(v=vs.80).aspx

Upvotes: 2

Related Questions