在SqlBulkCopy的使用NHibernate交易 [英] Using NHibernate transaction in SqlBulkCopy

查看:299
本文介绍了在SqlBulkCopy的使用NHibernate交易的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我存储使用NHibernate的一些数据,我需要将大量的数据为这一行动的一部分 - 在同一事务IE浏览器。 code是这样的:

I'm storing some data using NHibernate, and I need to insert huge amount of data as a part of this action - i.e. in the same transaction. Code looks like this:

using (ISession session = NHibernateHelper.OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
    session.SaveOrUpdate(something);
    // ...


    SqlBulkCopy bulkCopy = new SqlBulkCopy(
    (SqlConnection)session.Connection,
    SqlBulkCopyOptions.CheckConstraints | SqlBulkCopyOptions.FireTriggers,
    ???transaction???
    );
    //...

    transaction.Commit();
}

我知道我可以使用的TransactionScope还是在其他方面。但我坚持这种模式。让我们pretend的是,为了独立的数据库访问(如果我提取并注入任意容量插入操作)。 有没有办法如何让的SqlTransaction 实例了 NHibernate.ITransaction

I know that I could use TransactionScope or do it otherwise. But I insist on this pattern. Let's pretend that for the sake of independent DB access (if I extract and inject arbitrary bulk insert operation). Is there a way how to get SqlTransaction instance out of NHibernate.ITransaction?

感谢

推荐答案

不出所料,Ayende 解决这其中还有,但它是pretty的grody。

Unsurprisingly, Ayende tackled this one as well, but it's pretty grody.

它的要点是,你知道你可以争取正常ADO.NET中的NHibernate的交易 IDbCommand的情况下,像这样:

The gist of it is that you know you can enlist normal ADO.NET IDbCommand instances in the NHibernate transaction, like so:

var cmd = new SqlCommand ();
if (session.Transaction != null && session.Transaction.IsActive)
    session.Transaction.Enlist (cmd);

SqlBulkCopy的不是 IDbCommand的,并特别构造函数需要一个的SqlTransaction (这样你就已经跳过上提供独立的船反正)。所以欺骗 - 你的例子看起来是这样的:

But SqlBulkCopy isn't an IDbCommand, and that particular constructor requires a SqlTransaction (so you've already skipped the boat on provider-independence anyways). So cheat -- your example might look something like this:

using (var session = NHibernateHelper.OpenSession ())
using (var transaction = session.BeginTransaction ()) {
    using (var cmd = new SqlCommand ()) {
        transaction.Enlist (cmd);

        var bulk = new SqlBulkCopy ((SqlConnection)session.Connection,
                                    SqlBulkCopyOptions.CheckConstraints | SqlBulkCopyOptions.FireTriggers,
                                    (SqlTransaction)cmd.Transaction);
    }
    // ...
    transaction.Commit ();
}

您无疑会希望有一些错误检查,安全管型等。我不知道一个更现代/那么可怕的方式做到这一点,遗憾的是(甚至得到一个 IDbTransaction ITransaction )。

You'll undoubtedly want some error-checking, safe casts, etc. in there. I'm not aware of a more modern/less scary way to do this, unfortunately (even to get an IDbTransaction from an ITransaction).

这篇关于在SqlBulkCopy的使用NHibernate交易的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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