How can I execute this SQL query with .NET and Dapper.NET?

I have the following sql query:

BEGIN TRAN;

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

ROLLBACK TRAN;

and this is for a list of identifiers. eg.

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

then I expect it.

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;

Can this be done with Dapper ?

NOTE. If the meaning is TRANvery complicated, I can refuse it.

+4
source share
2 answers

Dapper has minimal support for internal query editing (it supports list expansion for IN, literal input and some tweaks OPTION/ UNKNOWN. Here you have two options:

  • StringBuilder, , ( )
  • 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();
    }
}
+2

- :

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

All Articles