我在Dapper ORM上设置了以下复杂模型并拒绝持久化:
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; }
}
}
这是我得到的错误:
The member PostData of type Foobar.Models.PostData cannot be used as a parameter value
尝试使用匿名对象:
const string sqlQuery =
"INSERT INTO Reports (created_at, post_name) VALUES (@CreatedAt, @PostName)";
_connection.Execute(sqlQuery, new { CreatedAt = report.CreatedAt,
PostName = report.PostData.PostName });
您所拥有的问题是您有效地尝试将PostData
对象作为名为PostData.PostName
的SQL参数的值PostData.PostName
。
请记住, "@parameter"
语法是原始SQL,而不是Dapper本身的功能。映射过程没有阶段涉及将SQL参数名称解释为针对您传递的对象的表达式。映射通过简单地将参数名称与属性名称匹配并从您传递的对象中注入相应的值来工作。