[英]Cant insert into Identity Column when Multithreading
我有一个数据迁移工具,直到最近看起来还不错。
我使用Parallel.Foreach遍历数据行的集合,计算一些要插入到表的新记录中的变量,然后运行SQL语句以插入数据。
Parallel.ForEach<DataRow>(dataTable.Rows, row =>
{
string reference = row["ref"].ToString();
int version = (int)row["version"];
string insertStatement = "INSERT INTO Item (Reference, Version) VALUES (@reference, @version)";
_database.ExecuteCommand(insertStatement, new SqlServerCeParameter[]
{
new SqlServerCeParameter("@reference", reference, SqlDbType.NVarChar),
new SqlServerCeParameter("@version", version, SqlDbType.Int),
});
});
public void ExecuteCommand(string sql, SqlServerCeParameter[] parameters)
{
//create the command that will execute the Sql
using (var command = new SqlCeCommand(sql, _connection))
{
//add any parameters
if (parameters != null) command.Parameters.AddRange(parameters.Select(p => p.ParameterBehind).ToArray());
try
{
//open the connection
if (_connection.State == ConnectionState.Closed) _connection.Open();
//execute the command
command.ExecuteNonQuery();
}
catch (SqlCeException ex)
{
//only catch if the native error is the duplicate value exception otherwise throw as normal
if (ex.NativeError != 25016) throw;
}
finally
{
//explicitly close command
command.Dispose();
}
}
}
但是我得到一个聚合异常,其内部异常如下:
{"The column cannot contain null values. [ Column name = ID,Table name = Item ]"}
该表的结构如下:
CREATE TABLE Item
(
ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
Reference NVARCHAR(50) NOT NULL,
Version INT NOT NULL
);
现在我不明白该错误,因为ID是一个身份列。
我曾经以为是因为多线程它不能同时计算两个id,但这似乎是一个脆弱的原因,因为SqlServerCe对于多用户环境是可以的。
重要说明: SQL CE对象不是线程安全的。 您在每个调用中都使用_connection
,我猜这是SqlCeConnection
的单个实例?
建议每个线程应使用自己的独立连接,而不是在多个线程之间共享它。 因此,尝试在ExecuteCommand
方法中创建一个新的SqlCeConnection
并每次进行连接。
这可能无法实现您希望/期望的速度提高,但是我不确定多线程是否如您期望的那样工作。 您需要多个内核/处理器才能使其有效,并且本身就是一个深层的话题。
确保该表的IDENTITY_INSERT为ON。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.