How to run Dapper/MySql queries in C# using user-defined variables
P粉546257913
P粉546257913 2023-08-25 23:41:09
0
2
412
<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粉546257913
P粉546257913

reply all(2)
P粉099985373

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.

P粉277305212

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!