0
votes

I tried insert to database with SqlBulkCopy but problem is when id on Sql server is identity(1,1) I have got this error "Cannot insert the value NULL into column 'two', table 'mydb.dbo.test'; column does not allow nulls. INSERT fails."

string connString = string.Format("Data Source={0};Initial Catalog={1};Integrated Security=True",DbServer,databaseName);
            DataTable table = new DataTable("test");
            //table.Columns.Add("id");
            table.Columns.Add("one", typeof(int));
            table.Columns.Add("two", typeof(int));

            DataRow row = table.NewRow();
            row["one"] = 1;
            row["two"] = 2;
            table.Rows.Add(row);

            DataRow row2 = table.NewRow();
            row2["one"] = 1;
            row2["two"] = 2;
            table.Rows.Add(row2);

            SqlBulkCopy bulk = new SqlBulkCopy(connString);
            bulk.DestinationTableName = "test";

            try
            {

                bulk.WriteToServer(table);
                bulk.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("error. {0}", ex.Message);
            }
            finally
            {
                bulk.Close();
            }

edit table scheme:

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[test](
    [id] [INT] IDENTITY(1,1) NOT NULL,
    [one] [INT] NOT NULL,
    [two] [INT] NOT NULL,
 CONSTRAINT [PK_test] PRIMARY KEY CLUSTERED 
(
    [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
1
Add following : table.Columns["two"].AllowDBNull= true; - jdweng
didn't understand relation between identity(1,1) on column id and column two - demo
Please show the definition of your SQL table. - Ian Kemp
@demo This table its just example but same problem everywhere where is id identity - DODO

1 Answers

1
votes

If your local table definition does not match the server's (it is missing the identity column), then you need to add an explicit mapping for each column (case-sensitive)

The first value is the name of the local source column, the second is destination column name.

bulk.ColumnMappings.Add("one", "one");
bulk.ColumnMappings.Add("two", "two");

This is also the case if the names don't match up exactly.