0

I have an entity like this. Let's say that name is the only :

public class MyEntity
{
    public Guid Id { get; set; } // immutable
    public string Name { get; set; } // can be changed

    // These are not exposed on the domain layer.  They're just bookkeeping fields.
    public string CreatedBy { get; set; }
    public DateTime DateCreated { get; set; }
    public string UpdatedBy { get; set; }
    public DateTime DateUpdated { get; set; }
}

If I populate the 2 "updated" fields before calling SaveChanges(), my entity will be erroneously marked changed if Name hasn't changed. Therefore, I need an event on the DbContext to hook into in order to populate those 2 fields just before committing the unit of work, but only on entities that have actually changed.

Does such an event exist? Can nHibernate do this?

Josh Kodroff
  • 27,301
  • 27
  • 95
  • 148
  • possible duplicate of [How can I add default values to a property when saving using Code First EF4.1?](http://stackoverflow.com/questions/5500464/how-can-i-add-default-values-to-a-property-when-saving-using-code-first-ef4-1) – Josh Kodroff Jun 13 '11 at 19:32

1 Answers1

3

In ObjectContext API you have event SavingChanges directly on ObjectContext. You can handle this event and use ObjectStateManager to find all modified / added entities and deal with them as you need.

In both ObjectContext API and DbContext API you can override SaveChanges method directly and do the same.

Fluent NHibernate is just NHibernate's extension for fluent mapping in code. NHibernate has much better support for such scenarios - it offers custom listeners to deal with this.

Community
  • 1
  • 1
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670