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?