【发布时间】:2021-07-04 09:44:02
【问题描述】:
我需要检查一条记录是否存在 - 如果是:则返回其 ID,如果不存在:创建一个新记录并返回其 ID。我在SELECT 中使用WITH (UPDLOCK, HOLDLOCK) 来防止重复(它会创建锁)。我想知道如果数据库中存在用于实现锁定的记录,我是否应该提交事务?
using (SqlConnection connection = new SqlConnection("..."))
{
await connection.OpenAsync();
using (var transaction = connection.BeginTransaction())
{
var locationId = await connection.QueryFirstOrDefaultAsync<int?>(
"SELECT id
FROM Locations WITH (UPDLOCK, HOLDLOCK)
WHERE regionId = @RegionId", new { RegionId = 1 }, transaction: transaction
);
if (locationId.HasValue)
{
//transaction.Commit(); // should I commit the transaction here?
return locationId.Value;
}
var location = new Location()
{
Name = "test",
RegionId = 1
};
var newLocationid = await connection.InsertAsync<int>(location, transaction);
transaction.Commit();
return newLocationid;
}
}
【问题讨论】:
-
@Charlieface without (UPDLOCK, HOLDLOCK) 我的数据库中有重复项,因为我在 regionId 列上没有唯一索引。
-
也许可以移除锁定提示,只使用唯一约束来防止重复?
-
@Stu 删除重复项并不是那么简单:(
标签: c# sql sql-server transactions