我们一直在使用Dapper
和Dapper.Contrib
来轻松执行常规数据库操作,这非常棒。但是,由于引入Polly
为我们的某些操作添加了重试策略,因为有必要检查记录的存在,我无法找到保持相同简单性的方法在执行重试之前。
以下是我们当前如何执行插入的简化示例:
public async Task Insert(Payment payment)
{
var retryPolicy = // Create using Polly.
using (var connection = new SqlConnection(_connectionString))
{
var dao = MapToDao(payment);
await retryPolicy.ExecuteAsync(() => connection.InsertAsync(dao));
}
}
[Table("Payment")]
public class PaymentDao
{
[ExplicitKey]
public Guid PaymentId { get; set; }
// A whole bunch of properties omitted for brevity
}
其中Payment
是我们的域模型,PaymentDao
是我们的数据访问对象。
我们确实在调用Insert
的服务中有逻辑检查重复项的逻辑,但重试策略否定了这一点。这意味着自Polly
引入以来,我们看到会插入少量重复付款。
我可以通过执行以下操作来解决此问题:
public async Task Insert(Payment payment)
{
var retryPolicy = // Create using Polly.
using (var connection = new SqlConnection(_connectionString))
{
var dao = MapToDao(payment);
await retryPolicy.ExecuteAsync(() => connection.ExecuteAsync(
@"IF ((SELECT COUNT(*) FROM dbo.Payment WHERE SubscriptionId = @subscriptionId) = 0)
BEGIN
INSERT INTO Payment
(
PaymentId,
SubscriptionId,
// Lots of columns omitted for brevity.
)
VALUES
(
@PaymentId,
@SubscriptionId,
// Lots of values omitted for brevity.
)
END",
new
{
dao.PaymentId,
dao.SubscriptionId,
// Lots of properties omitted for brevity.
}));
}
}
然而,正如你所看到的,它变得非常冗长。有没有更简单的方法呢?
答案 0 :(得分:2)
您可以考虑先使用模型进行检查,然后在搜索使用较少参数的情况下执行插入
using (var connection = new SqlConnection(_connectionString)) {
var dao = MapToDao(payment);
var sql = "SELECT COUNT(1) FROM dbo.Payment WHERE SubscriptionId = @subscriptionId";
await retryPolicy.ExecuteAsync(async () => {
var exists = await connection.ExecuteScalarAsync<bool>(sql, new {dao.SubscriptionId});
if(!exists) {
await connection.InsertAsync(dao);
}
});
}