Search code examples
c#ormdapper

Dapper ORM Nested Objects


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.


Solution

  • 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".