简体   繁体   中英

Dapper .NET: Customize Mapping

Model

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

Database

This is the table i want to query from

ErrorReports

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

The problem

So, what i want to do is querying the database and map the results into my model properties. But this doesn't work:

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

I understand that i have to explicitly say which columns map to which property, so, how can i do that?

You can return your query as dynamic and then map each property to your corresponding complex object.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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