Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error with Dapper – can't pass object as parameter into Execute method

I use .NET 6 and Package Dapper/2.1.15.
I have simple example

create table Test (a int, b varchar(10));

And in C#:

public class Test
{
    public int a { get; set; }
    public string b { get; set; }    
}

var insertStmt = @"insert into Test(a,b) values (@a, @b)";

var test = new Test {a = 1, b = "some value" };

connection.Execute(insertStmt,
            new
            {
                test
            });

I always get error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

System.Data.SqlClient.SqlException (0x80131904): Must declare the scalar variable "@a".

But according to some examples Dapper should "understand" that @a, @b are inside "test".

Of course I can list properties one by one

connection.Execute(insertStmt,
            new
            {
                test.a,
                test.b
            });

but feature should work.
And how it should work if I have collection of Test objects?

>Solution :

This should work:

var test = new Test {a = 1, b = "some value" };

connection.Execute(insertStmt, test);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading