IPreInsertEventListener makes object dirty, causes invalid update

Posted by Groxx on Stack Overflow See other posts from Stack Overflow or by Groxx
Published on 2011-03-08T23:57:08Z Indexed on 2011/03/09 0:10 UTC
Read the original article Hit count: 396

Filed under:
|

In NHibernate 2.1.2:

I'm attempting to set a created timestamp on insert, as demonstrated here. I have this:

public bool OnPreInsert(PreInsertEvent @event)
{
    if (@event.Entity is IHaveCreatedTimestamp)
    {
        DateTime dt = DateTime.Now;
        string Created = ((IHaveCreatedTimestamp)@event.Entity).CreatedPropertyName;
        SetState(@event.Persister, @event.State, Created, dt);
        @event.Entity.GetType().GetProperty(Created).SetValue(@event.Entity, dt, null);
    }

    // return true to veto the insert
    return false;
}

The problem is that doing this (or duplicating Ayende's example precisely, or reordering or removing lines) causes an update after the insert. The insert uses the correct "now" value, @p6 = 3/8/2011 5:41:22 PM, but the update tries to set the Created column to @p6 = 1/1/0001 12:00:00 AM, which is outside MSSQL's range:

Test 'CanInsertAndDeleteInserted' failed: System.Data.SqlTypes.SqlTypeException : SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.

I've tried the same thing with the PerformSaveOrUpdate listener, described here, but that also causes an update and an insert, and elsewhere there have been mentions of avoiding it because it is called regardless of if the object is dirty or not :/ Searching around elsewhere, there are plenty of claims of success after setting both the state and the object to the same value, or by using the save listener, or of the cause coming from collections or other objects, but I'm not having any success.

© Stack Overflow or respective owner

Related posts about nhibernate

Related posts about eventlistener