2

Using an NHibernate Event Listener, how do I access the previous entity state when an update occurs, so I can insert the replaced entity into my revisions table?

In SQL Server, I use the following trigger:

CREATE TRIGGER Trg_PostChange  
    ON dbo.Posts  
AFTER UPDATE  
AS  
BEGIN  
    SET NOCOUNT ON;  
    INSERT INTO [PostRevisions]  
        (...) -- columns here
    SELECT RevisionId = newid(),  
        ... -- columns here
    FROM DELETED -- contains the previous row column values
END

I have implemented a PostUpdateEventListener, but it appears that the Entity property of the PreUpdateEvent and PostUpdateEvent classes refer to the new entity state only.

Here is what I have so far:

public class PostEventListener : IPostUpdateEventListener
{
    public void OnPostUpdate(PostUpdateEvent eventItem)
    {
        var post = eventItem.Entity as Post;
        if (post != null)
        {
            var revision = new PostRevision((Post)eventItem.Entity);
            eventItem.Session.Save(revision);
        }
    }
}

Obviously OldState should contain the prior values, but it seems like a mission to map back to an object. Is there an easier way?

Petrus Theron
  • 27,855
  • 36
  • 153
  • 287

1 Answers1

0

You can try to use the EntityPersister, like so:

eventItem.Persister.Load(post.Id, null, LockMode.None, eventItem.Session);

If that doesn't work, you can always use a different session to load the object from the db.

Vadim
  • 17,897
  • 4
  • 38
  • 62
  • Is `eventItem.Persister.Load(...)` different from `eventItem.Session.Get(post.Id)`? – Petrus Theron Apr 25 '11 at 21:10
  • I believe it will call out to the db, but again if it doesn't then I think your only alternative is to use a different session. – Vadim Apr 25 '11 at 21:31