Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dapper ORM Nested Objects

Tags:

c#

orm

dapper

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.

like image 695
RWBear Avatar asked Jun 05 '12 23:06

RWBear


People also ask

Why Dapper is micro ORM?

Dapper is an example of Micro ORM, in fact, it is called the King of Micro ORM because of its speed and ease of work. First, it creates an IDbConnection object and allows us to write queries to perform CRUD operations on the database.

Is Dapper an ORM?

Dapper is an object–relational mapping (ORM) product for the Microsoft . NET platform: it provides a framework for mapping an object-oriented domain model to a traditional relational database. Its purpose is to relieve the developer from a significant portion of relational data persistence-related programming tasks.

Is Dapper a micro ORM?

Dapper is a popular open-source, micro-ORM solution that is compatible with the . NET application framework. It lets you work with strongly typed data that constantly changes without spending hours writing code. It is especially useful when dealing with unnormalized databases.

What is splitOn in dapper?

splitOn: CustomerId will result in a null customer name. If you specify CustomerId,CustomerName as split points, dapper assumes you are trying to split up the result set into 3 objects. First starts at the beginning, second starts at CustomerId , third at CustomerName .


1 Answers

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

like image 102
Alex Avatar answered Sep 22 '22 23:09

Alex