繁体   English   中英

Dapper .NET:自定义映射

[英]Dapper .NET: Customize Mapping

模型

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");
}

我知道我必须明确地说出哪些列映射到哪个属性,那么,我该怎么做?

您可以将查询返回为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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM