Dapper .NET:自定义映射

时间:2015-05-27 18:39:56

标签: c# .net dapper

模型

public class ErrorReport{
    public int? Id {get;set;}
    public ExceptionReport Exception {get;set;}
    public ExceptionReport InnerException {get;set;}
}

public class ExceptionReport{
    public string Type {get; set;}
    public string Message {get; set;}
}

数据库

这是我要从

查询的表格

ErrorReports

  • Id:int
  • ExceptionType:varchar
  • ExceptionMessage:varchar
  • InnerExceptionType:varchar
  • InnerExceptionMessage:varchar

问题

所以,我想要做的是查询数据库并将结果映射到我的模型属性中。但这不起作用:

using (var con = ConnectionFactory.CreateConnection(_connectionString))
{
     IEnumerable<ErrorReport> reports = con.Query<ErrorReport>("Select * from ErrorReports");
}

我明白我必须明确说明哪些列映射到哪个属性,所以,我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以将查询作为dynamic返回,然后将每个属性映射到相应的复杂对象。

using (var con = ConnectionFactory.CreateConnection(_connectionString))
{
    List<ErrorReport> reports = 
        con.Query<dynamic>("Select * from ErrorReports")
            .Select(x => new ErrorReport 
            { 
                Id = x.Id, 
                Exception = new ExceptionReport
                {
                    Type = x.ExceptionType,
                    Messsage = x.ExceptionMessage
                },
                InnerException = new ExceptionReport
                {
                    Type = x.InnerExceptionType,
                    Messsage = x.InnerExceptionMessage
                }
            }).ToList();
}