How to use Dapper with nested objects?

c# dapper orm

Question

I've never used Dapper ORM before, but I have a client that insists that I use it. With nested objects, I struggle. I have an embedded value object class in my main class, Location (Address). These are the two classes:

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

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

Using SQL

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

I've looked at a lot of examples, but I simply can't seem to build up the query properly. Simply put, I don't understand Dapper well enough to correctly construct it.

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

Accepted Answer

In your dapper query, you might use the "splitOn" argument.

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

If your objects in the record set aren't "divided" by a column called "Id," SplitOn is necessary.

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