Dapper Extension:具有复合字段的类,映射到单个表

时间:2016-07-06 18:25:18

标签: 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 class ProductContact
{
    public string FullName { get; set; }
    public string JobTitle { get; set; }
    public string Email { get; set; }
}

与此结构相关联的表“Publications”具有所有这些字段(包括ProductContact的属性)。

如果我尝试插入Publication行(包含ProductContact信息),程序将抛出异​​常:

System.NotSupportedException: The member Contact of type ProductContact cannot be used as a parameter value

所以,我添加了一个mapper来将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.Data.SqlClient.SqlException (0x80131904): Must declare the scalar variable "@FullName".

它表示Dapper完全忽略此属性,并且上一步中添加的映射没有效果。

有没有办法将ProductContact属性映射到表字段?

谢谢。

1 个答案:

答案 0 :(得分:2)

我认为DapperExtensions无法做到这一点。

one of their issues,他们说

  

目前,我们还没有计划支持嵌套对象。但是,你   可以创建自己的Mapper,允许跳过   嵌套对象

我尝试了各种方法和不同的映射类,无法实现任何目标 - 我不认为他们支持将嵌套属性值映射到忽略的任何方式属性本身(如果没有这样做,将导致"不能用作参数值"错误)。

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