我试图使用 SqlBulkCopy 作为一次执行多个INSERT的方法但由于某种原因,我在运行 WriteToServer(DataTable) 时遇到了一个唯一的约束违规 . 关于这个 SqlException 的奇怪之处在于它是这么说的 .
我的表架构:
CREATE TABLE Product (
ID INT IDENTITY (1, 1) PRIMARY KEY,
Name NVARCHAR(450) UNIQUE NOT NULL, -- Unique constraint being called
BulkInsertID NCHAR(6) -- Column the constraint is being called on
);
我能想到为什么会发生这种情况的唯一原因是因为我在 DataColumn 中分配列名时混淆了列名,但是我多次检查它们并且我找不到它们的任何问题 .
class Program
{
private static SqlConnection connection;
private static string connectionURL = "Server=ASUS-X750JA\\DIRECTORY;Database=directory;Integrated Security=True;";
private static Random _random = new Random();
public static SqlConnection openConnection()
{
connection = new SqlConnection(connectionURL);
connection.Open();
Console.WriteLine("Opened connection to DB");
return connection;
}
public static void closeConnection()
{
connection.Close();
Console.WriteLine("Closed connection to DB");
}
static void Main(string[] args)
{
List productNames = new List();
productNames.Add("Diamond");
productNames.Add("Gold");
productNames.Add("Silver");
productNames.Add("Platinum");
productNames.Add("Pearl");
addProducts(productNames);
}
private static void addProducts(List productNames)
{
const string tableName = "Product";
DataTable table = new DataTable(tableName);
string bulkInsertID;
do
{
bulkInsertID = generateID();
} while (isDuplicateBulkInsertID(tableName, bulkInsertID));
DataColumn nameColumn = new DataColumn("Name");
nameColumn.Unique = true;
nameColumn.AllowDBNull = false;
DataColumn bulkInsertIDColumn = new DataColumn("BulkInsertID");
bulkInsertIDColumn.Unique = false;
bulkInsertIDColumn.AllowDBNull = true;
table.Columns.Add(nameColumn);
table.Columns.Add(bulkInsertIDColumn);
foreach (string productName in productNames)
{
DataRow row = table.NewRow();
row[nameColumn] = productName;
row[bulkInsertIDColumn] = bulkInsertID;
table.Rows.Add(row);
}
using (SqlConnection connection = openConnection())
{
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
{
bulkCopy.DestinationTableName = table.TableName;
bulkCopy.WriteToServer(table);
}
}
}
///
/// Generates random 6-character string but it's not like GUID so may need to check for duplicates
///
///
public static string generateID()
{
char[] _base62chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".ToCharArray();
int length = 6;
var sb = new StringBuilder(length);
for (int i = 0; i < length; i++)
sb.Append(_base62chars[_random.Next(62)]);
return sb.ToString();
}
public static bool isDuplicateBulkInsertID(string tableName, string bulkInsertID)
{
string query = string.Format("SELECT BulkInsertID FROM {0} WHERE BulkInsertID = @bulkinsertid", tableName);
SqlCommand command = new SqlCommand(query, openConnection());
SqlParameter bulkInsertIDParam = new SqlParameter("@bulkinsertid", SqlDbType.NChar, bulkInsertID.Length);
bulkInsertIDParam.Value = bulkInsertID;
command.Parameters.Add(bulkInsertIDParam);
command.Prepare();
Task asyncTask = command.ExecuteReaderAsync();
SqlDataReader reader = asyncTask.Result;
bool isDuplicate = reader.HasRows;
closeConnection();
return isDuplicate;
}
}
屏幕截图中显示的唯一约束属于 Name 列,但重复键值正在发送到 BulkInsertID 列,我不知道为什么会抛出错误 .
编辑:我刚刚更改了我的架构,使用 uniqueidentifier 作为 bulkInsertID 列,并将 row[bulkInsertIDColumn] = bulkInsertID 更改为 row[bulkInsertIDColumn] = Guid.NewGuid().ToString() . 当我重新编写代码时,我发现生成的GUID已经运行但是当我查看表时,GUID位于名称列中 . 所以我可以得出结论,这不是服务器问题,而是程序中的问题 .