在我们的数据库表中,我们使用两个唯一的非聚集索引来创建跨四个字段的唯一约束。我们使用两个,因为其中一个字段ZipCode
是可空字段。如果表中存在null
ZipCode
条目的记录,我们不希望新记录与其他三个字段匹配但具有已定义ZipCode
的情况并添加(反之亦然)。
问题是似乎正在使用SqlBulkCopy
强制执行任何约束,因为您可以添加任何您喜欢的记录,而不管您已经在桌面上拥有什么。
在另一个程序中,我们使用Entity Framework
,因为我们正在加载少得多的数据。使用EF,这些约束完美地工作(它们目前正在生产中)。但是,使用SqlBulkCopy
它会被完全忽略。
T-SQL
CREATE UNIQUE NONCLUSTERED INDEX [UQ_ChannelStateEndDateZipCodeNOTNULL] ON [dbo].[ZipCodeTerritory]
(
[ChannelCode] ASC,
[StateCode] ASC,
[ZipCode] ASC,
[EndDate] ASC
)
WHERE ([ZipCode] IS NOT NULL)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [UQ_ChannelStateEndDateZipCodeISNULL] ON [dbo].[ZipCodeTerritory]
(
[ChannelCode] ASC,
[StateCode] ASC,
[ZipCode] ASC,
[EndDate] ASC
)
WHERE ([ZipCode] IS NULL)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
GO
C#
Dictionary<DataRow, string> faultyRows = new Dictionary<DataRow, string>();
using (SqlConnection connection = new SqlConnection(connString))
{
//Open Database connection
connection.Open();
//Create transaction objects
SqlTransaction transaction = connection.BeginTransaction();
SqlBulkCopy bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.CheckConstraints, transaction);
bulkCopy.DestinationTableName = "ZipCodeTerritory";
//Load data and initialize datatable
DataTable dataTable = LoadData(inserts);
IDataReader reader = dataTable.CreateDataReader();
DataTable dataSchema = reader.GetSchemaTable();
DataTable tmpDataTable = InitializeStructure();
//Create array to hold data being transfered into tmpDataTable
object[] values = new object[reader.FieldCount];
while (reader.Read())
{
//Clear temp table for single-record use
tmpDataTable.Rows.Clear();
//Get data for current row
reader.GetValues(values);
//Load values into the temp table
tmpDataTable.LoadDataRow(values, true);
//Load one record at a time
try
{
bulkCopy.WriteToServer(tmpDataTable);
transaction.Commit();
}
catch (Exception ex)
{
faultyRows.Add(tmpDataTable.Rows[0], ex.Message);
}
}
}
修改
我发现如果定义了ZipCode
字段,实际上会强制执行此约束。 ChannelCode
,StateCode
,ZipCode
,EndDate
字段的任何匹配都会产生SqlException
,其中包含以下Message
属性(从我跑的具体文字):
Cannot insert duplicate key row in object 'dbo.ZipCodeTerritory' with unique index 'UQ_ChannelStateEndDateZipCodeNOTNULL'. The duplicate key value is (9, WA , 98102 , 9999-12-31)
然而,这是我唯一一次能够解决我们的两个限制之一。
答案 0 :(得分:0)
这是因为我使用的方法将Model对象(我仍在使用实体框架)中的数据转移到DataRow
。以下是我现在使用的方法。在我的修复之前,ZipCode
字段(null
)将作为空字符串放入DataRow
列。由于这在技术上不是空字段,因此未触发约束。
private static DataTable LoadData(List<ZipCodeTerritory>zipCodeList, bool update = false)
{
DataTable dataTable = InitializeStructure();
foreach (var zipcode in zipCodeList)
{
DataRow row = dataTable.NewRow();
try
{
row[0] = zipcode.ChannelCode.Trim();
row[1] = zipcode.DrmTerrDesc.Trim();
row[2] = zipcode.IndDistrnId.Trim();
row[3] = zipcode.StateCode.Trim();
row[4] = (string.IsNullOrWhiteSpace(zipcode.ZipCode) ? null : zipcode.ZipCode.Trim());
row[5] = zipcode.EndDate.Date;
row[6] = zipcode.EffectiveDate.Date;
row[7] = zipcode.LastUpdateId;
row[8] = DateTime.Now.Date;
row[10] = zipcode.ErrorCodes;
row[11] = zipcode.Status;
//Add the Id column if we're doing an update
if(update) row[9] = zipcode.Id;
}
catch (Exception ex)
{
}
dataTable.Rows.Add(row);
}
return dataTable;
}