How to use Dapper with nested objects?

c# dapper orm

Question

I have a customer who has dictated that I use Dapper ORM, which I've never used before. I have a problem with nested objects. I have a main class (Location) which has an embedded value object class (Address). The two classes look like this:

class Location {
    int Id;
    string LocationName;
    Address LocationAddress;
}

Class Address {
    string Street;
    string City;
    string State;
    string ZipCode;
}

The SQL:

SELECT Id, LocationName, Street, City, State, ZipCode FROM Locations

I've look at a number of examples but I just can’t get the query set up right. I just don't understand Dapper enough to get the structure right.

1
10
9/25/2019 11:44:17 AM

Accepted Answer

You could use the "splitOn" parameter in your dapper query.

var sql = "SELECT Id, LocationName, Street, City, State, ZipCode FROM Locations";
var conn = // your get connection logic here. 

using(conn)
{
 conn.Open();
 var locations = conn.Query<Location,Address,Location>(sql, (location, address) => 
                 {
                   location.LocationAddress = address;
                   return location;
                 }, splitOn: "Street");
}

SplitOn is required if your objects in the record set aren't "split" by a column named "Id".

10
6/8/2012 5:48:06 AM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow