Home > Blockchain >  C# - Dapper/MySql - How to run a query with user-defined variable
C# - Dapper/MySql - How to run a query with user-defined variable

Time:03-12

I've been trying to run this code:

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

But I get the following exception:

System.NullReferenceException: 'Object reference not set to an instance of an object.'
This exception was originally thrown at this call stack:
  MySql.Data.MySqlClient.MySqlConnection.Reader.set(MySql.Data.MySqlClient.MySqlDataReader)

My first guess is that the variable is being treated as a SqlParameter, and since I'm not passing any argument to it, my code fails. Is there a way to run a query like that using Dapper?

CodePudding user response:

Or you can else write your sql with a valid sql variable declaration :

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

Note : tested with Sql Server, not MySql. I don't use it.

CodePudding user response:

The NullReferenceException you are receiving is likely because you have not defined foo as a parameter.

  using (var db = new MySqlConnection(@"mysql_connstr_here"))
  {
    var sql = dbConnection.QueryFirstOrDefault<int>(
      @" 
      select @foo;",
      new
      {
        foo = userAssignedVariable
      });
  }

CodePudding user response:

I've found this in the Dapper documentation:

In order to use Non-parameter SQL variables with MySql Connector, you have to add the following option to your connection string:

Allow User Variables=True

Make sure you don't provide Dapper with a property to map.

So all I needed to do was to Allow User Variables=True to the connection string. It worked.

  • Related