在具有GUID主键和默认newsequentialid()的表上使用SQLBulkCopy时
例如
CREATE TABLE [dbo].[MyTable]( [MyPrimaryKey] [uniqueidentifier] NOT NULL CONSTRAINT [MyConstraint] DEFAULT (newsequentialid()), [Status] [int] NULL, [Priority] [int] NULL, CONSTRAINT [PK_MyTable] PRIMARY KEY NONCLUSTERED ( [MyPrimaryKey] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
与C#代码
tran = connection.BeginTransaction(); SqlBulkCopy sqlCopy = new SqlBulkCopy(connection,SqlBulkCopyOptions.Default, tran); sqlCopy.DestinationTableName = "MyTable"; sqlCopy.WriteToServer(dataTable);
给你一个错误......
列'MyPrimaryKey'不允许DBNull.Value
我试过摆弄SqlBulkCopyOptions.唯一有效的方法是将MyPrimaryKey字段设置为允许空值并删除主键.
任何人都知道这个问题是否有解决方法?或者您可以验证没有解决方法(除了更改表结构)?
您需要设置列映射.第一次打电话
sqlCopy.ColumnMappings.Clear();
然后打电话
sqlBulkCopy.ColumnMappings.Add("Status", "Status"); sqlBulkCopy.ColumnMappings.Add("Priority", "Priority");
这意味着批量复制将停止尝试插入MyPrimaryKey列,并且只会插入status和Priority列.