Home  >  Q&A  >  body text

How to run Dapper/MySql queries in C# using user-defined variables

<p>I've been trying to run this code: </p> <pre class="brush:php;toolbar:false;">using System; using Dapper; using MySql.Data.MySqlClient; namespace DapperTests { class Program { static void Main(string[] args) { using (var db = new MySqlConnection(@"mysql_connstr_here")) { var sql = @" set @foo := (select count(*) from table1); select table2.*, @foo from table2;"; var result = db.Query(sql); } Console.ReadLine(); } } }</pre> <p>But I get the following exception: </p> <pre class="brush:php;toolbar:false;">System.NullReferenceException: 'The object reference is not set to an instance of the object. ' This exception was initially thrown in this call stack: MySql.Data.MySqlClient.MySqlConnection.Reader.set(MySql.Data.MySqlClient.MySqlDataReader)</pre> <p>My initial guess was that the variable was treated as a SqlParameter, and since I wasn't passing any parameters, my code failed. Is there a way to run a query like this using Dapper? </p>
P粉546257913P粉546257913421 days ago410

reply all(2)I'll reply

  • P粉099985373

    P粉0999853732023-08-26 19:23:05

    Or you can write your SQL statements using valid SQL variable declarations:

    var sql = @"declare @foo int = 0; select @foo;";

    Note: This code has been tested on Sql Server and does not apply to MySql. I don't use it.

    reply
    0
  • P粉277305212

    P粉2773052122023-08-26 15:45:16

    I found this in the Dapper documentation:

    So all I need to do is add Allow User Variables=True to the connection string. It worked.

    reply
    0
  • Cancelreply