views:

27

answers:

1

Hi all

I'm overriding NHibernate's PreInsertEventListener in order to set the entity's DateCreated property to DateTime.Now.

Here is my code:

public bool OnPreInsert(PreInsertEvent e)
{
  DomainObject domainObject = (DomainObject) e.Entity;
  if (domainObject.CreatedById == 0) throw new Exception("The " + domainObject.GetType().Name + " cannot be created if its CreatedById property has not been set.");
  domainObject.DateCreated = DateTime.Now;
  return false;
}

I am finding that any entity properties set here (for example, the call to DateCreated above) do not find their way into the update SQL created by NHibernate. Does anyone know what gives?

Yes, I have cofirmed that my event listener is being called!

Thanks

David

+1  A: 

Hmmm, it seems you have to use a specific syntax to modify the entity's properties at this stage of the game.

That syntax is demonstrated here:

http://stackoverflow.com/questions/2365750/why-both-nhibernate-onpreinsert-and-onpreupdate-methods-get-called-for-an-object

Note that I've discovered you don't also have to set the entity's properties the normal way as well, which this code does.

Thanks

David

David
Correct, a few additional enhancements I can suggest here: 1) Use an interface that exposes the property and property name from the entity (eg. DateCreated and DateCreatedPropertyName) 2) Use a base class for your interceptors that contains the SetProperty logic (or use a helper class to keep this usage consistent)
DanP
Thanks for the suggestions. Can I just ask for the rationale for the first?
David
@David: This allows you to use the interceptor for multiple entities that may require it, the property name is usually a good idea unless you're certain that all entities will use the exact same property name that the interface exposes (since you need a string version of it for the 'set' call) - make sense?
DanP
I see what you mean - thanks. In this case, all domain objects extend the DomainObject abstract class that contains the DateCreated property, so all domain objects have the same name for the property.
David
Hey! You're the same guy who answered my previous NHibernate question. Thanks and good work!
David
@David: No worries, also be sure to check if the domainObject is null after the cast before attempting to assign the properties :)
DanP