Multiple SQL statements in one roundtrip using Dapper.NET

后端 未结 2 543
后悔当初
后悔当初 2020-12-13 05:53

There is a nice feature in ADO.NET that allows you to send multiple SQL statements to database in one roundtrip and receive results for all statements:

var c         


        
2条回答
  •  臣服心动
    2020-12-13 06:15

    Yes, the Dapper QueryMultiple extension can do that:

    string query = @"SELECT COUNT(*) FROM TABLEA;
                     SELECT COUNT(*) FROM TABLEB";
    using (var multi = connection.QueryMultiple(query, null))
    {
        int countA = multi.Read().Single();
        int countB = multi.Read().Single();
    }     
    

    According to Marc Gravell this is the ideal way to execute multiple queries in a single batch.

    Note: Dapper creator Sam Saffron has posted a detailed explanation with code sample on using QueryMultiple to accomplish this.

    UPDATE: I add the important comment from Marc

    Note: from 1.5-ish (a little earler on the alpha builds) there is a ReadSingle() method that may be more convenient and efficient than Read().Single()

提交回复
热议问题