nhibernatefluent-nhibernatesqlbulkcopyfluent-nhibernate-mappingidentity-column

nHibernate BulkInsert Identity column?


Question: I'm bulk-inserting data from XML using nHibernate (fluent)

I read the XML file into a datatable, then create a List from it. Afterwards, I run BulkInsert on that list.

Like this:

    // 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();
            }
        }
    }

It works fine, just that the User-ID (Auto-ID) is newly assigned.

This is 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

How can I insert the users and preserve the IDs with nHibernate ? I need to insert the user-group mapping afterwards, so this will fail if IDs change...

.NET & SqlClient has SqlBulkCopy and

System.Data.SqlClient.SqlBulkCopyOptions.KeepIdentity

for that.

But what has nHibernate ?

And while I am at it, what does it have for

System.Data.SqlClient.SqlBulkCopyOptions.KeepNulls

Solution

  • you can create a temporary Sessionfactory. Assuming you have

    private ISessionFactory CreateSessionFactory(Action<Configuration> addconfigure)
    

    and code

    var sessionFactory = CreateSessionFactory(config =>
        ((SimpleValue)config.GetClassMapping(typeof(User)).Identifier)
            .IdentifierGeneratorStrategy = "assigned");