0

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
Pleun
  • 8,836
  • 1
  • 28
  • 46
Stefan Steiger
  • 68,404
  • 63
  • 337
  • 408

1 Answers1

0

Try correct mapping with:

mapping => mapping.Id(x => x.Id).GeneratedBy.Assigned()
Anton
  • 1,533
  • 12
  • 17
  • But ... Id(x => x.BE_ID).GeneratedBy.Identity().Column("BE_ID"); is fundamentally correct, I want it to be a generated idendity (later on, one can create users in the BackOffice). I just want to switch off auto-assigning for the initial table population. – Stefan Steiger Mar 19 '12 at 13:18