如果实体尚未存在,则插入该实体

时间:2018-04-08 17:41:31

标签: c# dapper dapper-contrib

我们一直在使用DapperDapper.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.
            }));
    }
}

然而,正如你所看到的,它变得非常冗长。有没有更简单的方法呢?

1 个答案:

答案 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);
        }
    });
}