C# Dapper扩展:具有复合字段的类,映射到单个表

C# Dapper扩展:具有复合字段的类,映射到单个表,c#,.net,dapper,dapper-extensions,C#,.net,Dapper,Dapper Extensions,我有以下课程: public class Publication { public int Id { get; set; } public string Title { get; set; } public string Headline { get; set; } public DateTime Published { get; set; } public ProductContact Contact { get; set; } } public cl

我有以下课程:

public class Publication
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Headline { get; set; }
    public DateTime Published { get; set; }
    public ProductContact Contact { get; set; }
}

public class ProductContact
{
    public string FullName { get; set; }
    public string JobTitle { get; set; }
    public string Email { get; set; }
}
与此结构关联的表“Publications”包含所有这些字段(包括ProductContact的属性)

如果我尝试插入出版物行(包含ProductContact信息),程序将引发异常:

System.NotSupportedException: The member Contact of type ProductContact cannot be used as a parameter value
System.Data.SqlClient.SqlException (0x80131904): Must declare the scalar variable "@FullName".
因此,我添加了一个映射器,将ProductContact属性映射到properties表中的字段:

  public PublicationMapper ()
    {
        TableName = "Publications";

        Map(x => x.Contact.FullName).Column("ContactFullName");
        Map(x => x.Contact.JobTitle).Column("ContactJobTitle");
        Map(x => x.Contact.Email).Column("ContactEmail");

        AutoMap();
    }
有了这个映射器,我得到了同样的异常

然后,我为Contact字段添加了ignore语句,告诉Dapper不要在insert语句中包含这个元素

            Map(x => x.Contact).Ignore();
在这种情况下,我得到另一个例外:

System.NotSupportedException: The member Contact of type ProductContact cannot be used as a parameter value
System.Data.SqlClient.SqlException (0x80131904): Must declare the scalar variable "@FullName".
它表示Dapper完全忽略此属性,并且在上一步中添加的映射无效

是否有办法将ProductContact属性映射到表字段


谢谢。

我认为DapperExtensions不可能做到这一点

他们说,在中国

目前,我们不打算支持嵌套对象。然而,你 可以创建自己的映射程序,允许跳过 嵌套对象

我尝试了各种方法和不同的映射类,但都没有成功——我认为它们不支持任何映射嵌套属性值和忽略属性本身的方法(如果不这样做,将导致“不能用作参数值”错误)


一种方法是手动将对象展平到一个匿名类中(正如@juharr在对您的问题的评论中所建议的),另一种方法是使用类似AutoMapper的东西将复杂对象展平到一个展平的插入模型中。

为什么不只是一个匿名类
新建{pub.Id,pub.Title,…,ContactFullName=pub.Contact.FullName,ContactJobTitle=pub.Contact.JobTitle,ContactEmail=pub.Contact.Email}
?虽然听起来像是
ContactFullName
实际上应该是
FullName
,以便与SQL中的参数名匹配。显示SQL和完整的Dapper调用在这里也会有所帮助。不幸的是,它不能/不会这样做。我发现自己正处于这个位置,试图向管理层表明Dapper是解决问题的方法去帮助减少代码和易用性。特别是当对象和它们的数据对应物有不同的名称时。好吧