1

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?

1 Answer 1

2

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();
}
Sign up to request clarification or add additional context in comments.

4 Comments

But does not have an overhead? I mean... you map all the items to a model, and then re-execute the foreach again...
@ArielScherman The overhead is negligible and mostly tied up in the use of dynamic unless you're bulk reading hundreds of thousands of records (and even then, profiling might not show much of a performance gap). In addition, IEnumerable is returned, meaning that we will only be iterating once..
Is it really be iterated just once? Isn't a two step process? (first from records to dynamic, then from dynamic to object)
@ArielScherman Correct, it is a two step process in terms of object transformation, but because we select to a new object off of IEnumerable<dynamic>, that transformation occurs during a single iteration. The objects do change twice, but the rows returned are iterated once. Now, if you called ToList() on your collection BEFORE selecting new objects, yes, you would be iterating twice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.