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

时间:2015-03-19 07:10:19

标签: c# .net dapper

我有以下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使这很难,我可以放弃它。

2 个答案:

答案 0 :(得分:3)

Dapper在内部对更改查询的支持很少(它支持IN的列表扩展,文字注入以及一些OPTION / UNKNOWN调整。这里有两个选择:

  1. 使用StringBuilder创建一个可以执行的大型操作(可以通过字典进行参数化)
  2. 将事务移至ADO.NET而非TSQL
  3. 对于后者,可能是这样的:

    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();
        }
    }
    

答案 1 :(得分:1)

你可以这样做:

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();
    }
}