views:

36

answers:

1

Hi all

I'm trying to use NHibernate in a project. All my domain tables include a 'CreatedBy' field which is a foreign key to the Users table. Since this is an ASP.NET app, the only information I have about the user at the time of saving is the username, from the cookie.

What is the best approach for obtaining the user ID and saving it into the domain table's CreatedBy field?

For example, it would be simple to write code in the app to load the user up from the username, and stick its UserId property into the CreatedBy property of the domain object before saving it. However, this would be clumsy (I would have to remember to do all this whenever persisting a newly-created domain object) and would also involve two hits to the database, which I would rather avoid.

What is the simplest and most elegant way to do this?

Thanks

David

+1  A: 

Event listeners is the way to go; you can see a tutorial covering this here: Creating an Audit Log using NHibernate Events

DanP
Yes, it looks as if the options are this one, or use the <sql-insert> element in the mapping file to call a sproc. Thanks
David
David, I would recommend the interceptor approach, and have all applicable entities implement a common interface - this is probably the most DRY method available. We do this for things such as IHaveCreationDate, IHaveLastModifiedDate, etc.
DanP