Persisting complex objects with Dapper ORM

c# dapper

Question

I have the following complex models setup on my Dapper ORM and it refuses to persist:

const string sqlQuery = "INSERT INTO Reports (created_at, post_name) VALUES (@CreatedAt, @PostData.PostName)";
_connection.Execute(sqlQuery, report);

namespace Foobar.Models
{
    public class Report
    {
        public int Id { get; set; }
        public DateTime CreatedAt { get; set; }
        public PostData PostData { get; set; }
    }

    public class PostData
    {
        public string title { get; set; }
        public double index { get; set; }
    }
}

This is the error i'm getting:

The member PostData of type Foobar.Models.PostData cannot be used as a parameter value

Accepted Answer

Try using an anonymous object:

const string sqlQuery =
    "INSERT INTO Reports (created_at, post_name) VALUES (@CreatedAt, @PostName)";

_connection.Execute(sqlQuery, new { CreatedAt = report.CreatedAt,
                                    PostName = report.PostData.PostName });

The problem with what you have is that you are effectively trying to pass the PostData object as a value for an SQL parameter called PostData.PostName.

Bear in mind that the "@parameter" syntax is raw SQL, not a feature of Dapper itself. There's no stage of the mapping process that involves interpreting the SQL parameter name as an expression against the object that you pass. The mapping works by simply matching a parameter name to a property name and injecting the corresponding value from the object you pass.




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why