0

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.

2
  • What would using triggers accomplish? Jun 21, 2011 at 19:43
  • @Per Hornshøj-Schierbeck, using a SQL UPDATE trigger I could check that the FavoriteBook column is about to change, and stamp the current time in the FavoriteBookLastUpdated column. That's exactly what I'd like to do but in code instead. Jun 21, 2011 at 19:49

2 Answers 2

3

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();
}
2

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

2
  • +1 Yes. If you want to change another property together with currently changing it looks like a case for custom property setter doing all the stuff. That has nothing to do with EF. Jun 22, 2011 at 6:56
  • @Ladislav, Perfect. I should have just tried that from the start. I was over-thinking this. I created a custom public property setter (and getter) for FavoriteBook that also updates the lastupdated property. Simple. Jun 22, 2011 at 13:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.