Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dapper simple mapping

Table:

create table Documents 
   (Id int, 
    SomeText varchar(100), 
    CustomerId int, 
    CustomerName varchar(100)
   )

insert into Documents (Id, SomeText, CustomerId, CustomerName) 
   select 1, '1', 1, 'Name1' 
     union all
   select 2, '2', 2, 'Name2'

Classes:

public class Document
{
    public int Id { get; set; }
    public string SomeText { get; set; }
    public Customer { get; set; }
}

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
}

How can I get all Documents with their Customers with Dapper? This gives me all documents, but the customer is null (of course):

connection.Query<Document>("select Id, SomeText, CustomerId, CustomerName from Documents")...

EDIT - similar, but more advanced mapping question: Dapper intermediate mapping

like image 879
sventevit Avatar asked Apr 16 '12 08:04

sventevit


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 better than Entity Framework?

Dapper vs Entity Framework CoreDapper is literally much faster than Entity Framework Core considering the fact that there are no bells and whistles in Dapper. It is a straight forward Micro ORM that has minimal features as well.

Is Dapper ORM free?

Dapper is free as open source software that is distributed under dual license, either the Apache License 2.0 or the MIT License.

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.


2 Answers

Example taken from dapper project page (see the Multi Mapping section):

var sql = 
@"select * from #Posts p 
left join #Users u on u.Id = p.OwnerId 
Order by p.Id";

var data = connection.Query<Post, User, Post>(sql, (post, user) => { post.Owner = user; return post;});
var post = data.First();

post.Content.IsEqualTo("Sams Post1");
post.Id.IsEqualTo(1);
post.Owner.Name.IsEqualTo("Sam");
post.Owner.Id.IsEqualTo(99);
like image 132
AdaTheDev Avatar answered Sep 30 '22 13:09

AdaTheDev


var docs = connection.Query<Document, Customer, Document>(
    "select Id, SomeText, CustomerId as [Id], CustomerName as [Name] from Documents",
    (doc, cust) => { doc.Customer = cust; return doc; }).ToList();
like image 44
Marc Gravell Avatar answered Sep 30 '22 14:09

Marc Gravell