I'm trying to use SqlBulkCopy
to insert a number of rows into a table where the Id column is set with a sequence. The sequence and table look something like:
CREATE SEQUENCE [dbo].[MyTableId]
AS [int]
START WITH 1
INCREMENT BY 1
MINVALUE -2147483648
MAXVALUE 2147483647
CACHE 10
GO
CREATE TABLE [dbo].[MyTable](
[Id] [int] NOT NULL,
[SomeColumn] [int] NOT NULL,
[AnotherColumn] [nvarchar](100) NOT NULL
CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED
(
[Id] ASC
)
GO
ALTER TABLE [dbo].[MyTable] ADD
CONSTRAINT [DF_MyTable_Id]
DEFAULT (NEXT VALUE FOR [MyTableId]) FOR [Id]
GO
The Code to import the rows looks something like:
var table = new DataTable();
using (var adapter = new SqlDataAdapter($"SELECT TOP 0 * FROM dbo.MyTable", conn))
{
adapter.Fill(table);
}
foreach (Data d in data)
{
var row = table.NewRow();
row["SomeColumn"] = d.someColumnValue;
row["AnotherColumn"] = d.anotherColumnValue;
table.Rows.Add(row);
}
using (var bulk = new SqlBulkCopy(conn))
{
bulk.DestinationTableName = "dbo.MyTable";
bulk.WriteToServer(table);
}
This fails when writing the data to the server because
System.InvalidOperationException: 'Column 'Id' does not allow DBNull.Value.'
I have tried removing the Id column from the table definition, but this just puts the column ordinals off by one. I've tried setting the Id row to:
table.Columns["Id"].AutoIncrement = true;
but this ignores the sequence, and on repeated runs of the import, restarts the auto-increment value from 0.
How would I instruct the server to generate a new Id value using its sequence? Or is it possible to separately generate a number of values for the sequence prior to creating the new rows in the table?