如何使用 .NET 和 Dapper.NET 执行此 sql 语句?

How can I execute this sql statement with .NET and Dapper.NET?

我有以下 sql 查询:

BEGIN TRAN;

UPDATE [dbo].[Foo] SET StatusType = 2 WHERE FooId = xxx;
INSERT INTO [dbo].[FooNotes] (FooId, Note) VALUES ('blah....', xxx);

ROLLBACK TRAN;

这是一个 ID 列表。 例如

var fooIds = new [] { 1, 2, 3, 4, 5, 6 };

那么我期待这个..

BEGIN TRAN;

UPDATE [dbo].[Foo] SET StatusType = 2 WHERE FooId = 1;
INSERT INTO [dbo].[FooNotes] (FooId, Note) VALUES ('blah....', 1);

UPDATE [dbo].[Foo] SET StatusType = 2 WHERE FooId = 2;
INSERT INTO [dbo].[FooNotes] (FooId, Note) VALUES ('blah....', 2);

UPDATE [dbo].[Foo] SET StatusType = 2 WHERE FooId = 3;
INSERT INTO [dbo].[FooNotes] (FooId, Note) VALUES ('blah....', 3);

ROLLBACK TRAN;

Dapper可以做到吗?

注意:如果 TRAN 让这变得困难,我可以放弃它。

你可以这样做:

using (var connection = new SqlConnection(yourConnectionString))
{
    connection.Open();
    using (var tx = connection.BeginTransaction())
    {
        foreach (var fooId in fooIds)
        {
            connection.Execute("UPDATE [dbo].[Foo] SET StatusType = 2 WHERE FooId = @id; INSERT INTO [dbo].[FooNotes] (FooId, Note) VALUES ('blah....', @id);", new {id = fooId}, tx);
        }

        tx.Rollback();
    }
}

Dapper 对内部 改变 查询的支持很少(它支持 IN 的列表扩展、文字注入和一些 OPTION/UNKNOWN 调整。你有两个选择:

  1. 使用StringBuilder创建一个可以执行的大型操作(这可以通过字典参数化)
  2. 将事务移动到 ADO.NET 而不是 TSQL

对于后者,可能是这样的:

using(var tran = conn.BeginTransaction())
{
    try
    {
        conn.Execute(@"
UPDATE [dbo].[Foo] SET StatusType = 2 WHERE FooId = @id;
INSERT INTO [dbo].[FooNotes] (FooId, Note) VALUES ('blah....', @id);",
            fooIds.Select(id => new { id }), transaction: tran);
    }
    finally // in this example, we always want to rollback
    {
        tran.Rollback();
    }
}