Search code examples
c#sql-serverasp.net-coredapper

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:

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