nHibernate BulkInsert标识列?

时间:2012-03-19 12:37:58

标签: nhibernate fluent-nhibernate sqlbulkcopy fluent-nhibernate-mapping identity-column

问题:我使用nHibernate(流畅)

从XML批量插入数据

我将XML文件读入数据表,然后从中创建一个List。 之后,我在该列表上运行BulkInsert。

像这样:

    // http://stackoverflow.com/questions/982295/saving-1000-records-to-the-database-at-a-time
    public static void BulkInsert(List<dynamic> ls)
    {
        //List<DB.Tables.T_Users> ls = new List<DB.Tables.T_Users>();
        // Read from DataTable


        var sessionFactory = CreateSessionFactory();

        //using (ISession session = sessionFactory.OpenSession())

        // http://davybrion.com/blog/2008/10/bulk-data-operations-with-nhibernates-stateless-sessions/
        using (IStatelessSession session = sessionFactory.OpenStatelessSession())
        {
            using (var tx = session.BeginTransaction())
            {
                session.SetBatchSize(ls.Count);
                foreach (var objThisItem in ls)
                {
                    //session.SaveOrUpdate(objThisItem);
                    session.Insert(objThisItem);
                }
                tx.Commit();
            }
        }
    }

它工作正常,只是新分配了用户ID(自动ID)。

这是T_User

CREATE TABLE [dbo].[T_User](
    [USR_ID] [int] IDENTITY(1,1) NOT NULL,
    [USR_Name] [nvarchar](50) NULL,
    [USR_Prename] [nvarchar](50) NULL,
    [USR_User] [nvarchar](50) NULL,
    [USR_Password] [nvarchar](50) NULL,
    [USR_Language] [nvarchar](5) NULL,
    [USR_Hash] [nvarchar](50) NULL,
    [USR_isLDAPSync] [bit] NOT NULL,
    [USR_Domaene] [nvarchar](255) NULL,
    [USR_Hide] [bit] NOT NULL,
PRIMARY KEY CLUSTERED 
(
    [USR_ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

如何插入用户并使用nHibernate保留ID? 我之后需要插入用户组映射,因此如果ID更改,这将失败...

.NET&amp; SqlClient有SqlBulkCopy 和

System.Data.SqlClient.SqlBulkCopyOptions.KeepIdentity

为此。

但是什么有nHibernate?

虽然我在这,但它有什么用于

System.Data.SqlClient.SqlBulkCopyOptions.KeepNulls

1 个答案:

答案 0 :(得分:0)

尝试使用正确的映射:

mapping => mapping.Id(x => x.Id).GeneratedBy.Assigned()