5

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

Community
  • 1
  • 1
sventevit
  • 4,766
  • 10
  • 57
  • 89
  • 2
    A big thanks for providing, in the question, the necessary SQL schema, c# classes, and your current code. It is much appreciated, and makes for a very well written question. – Marc Gravell Apr 16 '12 at 08:49
  • @MarcGravell: Very well said. +1'd this question just for this fact, so OP gets even more encouraged to participate in this community. – Robert Koritnik Apr 17 '12 at 07:10

2 Answers2

6

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);
AdaTheDev
  • 142,592
  • 28
  • 206
  • 200
  • Thanks, this works great but I simplified my question too much - this is my real problem: http://stackoverflow.com/questions/10223620/dapper-intermediate-mapping :) – sventevit Apr 19 '12 at 07:40
4
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();
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Thanks, this works great but I simplified my question too much - this is my real problem: http://stackoverflow.com/questions/10223620/dapper-intermediate-mapping :) – sventevit Apr 19 '12 at 07:40
  • I have similar classes and two table of database. I JOIN this two table but I'm getting this error: When using the multi-mapping APIs ensure you set the splitOn param if you have keys other than Id – Lorenzo Belfanti Apr 20 '16 at 15:33