开发者

Emulate AFTER UPDATE ... FROM DELETED Trigger with NHibernate Event Listener

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 Enti开发者_如何学Pythonty 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜