OnPost事件在提交之前运行 [英] OnPost events run before a commit

查看:143
本文介绍了OnPost事件在提交之前运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一些像这样的标准NHibernate代码,它会写入SQL数据库:

Say I have some standard NHibernate code like this, which writes to an SQL database:

using (var session = SessionFactory.OpenSession())
{
  using (var tx = session.BeginTransaction())
  {
      var customer = session.Get<Customer>(id);
      customer.Property1 = "new value";
      customer.Property2 = "new value";
      tx.Commit();
  }
}

我正在尝试为客户(在NoSQL数据库中)创建一个副本表.因此,当上面的代码运行时,将运行以下事件处理程序:

I am trying to create a copy table for the Customer (in a NoSQL database). Therefore when the code above runs the following event handler runs:

public void OnPostUpdate(PostUpdateEvent postUpdateEvent)
        {
            if (postDeleteEvent.Entity.GetType() == typeof(Customer)) 
            {
                var customer = (Customer)postUpdateEvent.Entity;
                customerCopyRepository.Update(customer);
            }
        }

如果我要将第一个代码片段更改为插入片段,那么它将运行:

If I was to change the first code fragment to an insert, then this would run:

 public void OnPostInsert(PostInsertEvent postInsertEvent)
        {
            if (postInsertEvent.Entity.GetType() == typeof(Customer))  
            {
                var customer = (Customer)postInsertEvent.Entity;
                customerCopyRepository.Insert(customer);
            }
        }

,当删除发生时运行:

public void OnPostDelete(PostDeleteEvent postDeleteEvent)
        {
            if (postDeleteEvent.Entity.GetType() == typeof(Customer)) 
            {
                var customer = (Customer)postDeleteEvent.Entity;
                customerCopyRepository.Delete(customer.Id);
            }
        }

CustomerCopyRepository被注入到类构造函数中.

CustomerCopyRepository is injected into the class constructor.

这非常好用.我唯一的问题是,上面的每个事件似乎都在将数据提交到数据库之前运行.因此,可能会发生以下情况:

This is working very nicely. The only problem I have is that each of the events above seem to run before the data is committed to the database. Therefore the following scenario could occur:

1)将客户写入NoSQL数据库.

1) Write Customer to NoSQL database.

2)由于SQL错误,未将客户写入SQL数据库.

2) Customer is not written to SQL database(because of an SQL error).

有什么办法可以防止这种情况发生?

Is there any way I can prevent this scenario?

推荐答案

我有完全相同的场景(与ElasticSearch同步),最后我使用了RegisterSynchronization方法:

I have exactly the same scenario (Sync with ElasticSearch) and I ended up by using the RegisterSynchronization method:

private void Sync(IPostDatabaseOperationEventArgs e)
{
    e.Session.Transaction.RegisterSynchronization(new AfterTransactionCompletes(success =>
    {
        if (!success)
            return;

        // Do your stuff
    }));
}

这篇关于OnPost事件在提交之前运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆