webworm
webworm

Reputation: 11019

Trying to understand Dapper Multi Mapping

I have been going through Dapper's Multi Mapping documentation but remain confused.

This is the example from Dapper documentation

class Post
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public User Owner { get; set; }
}

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

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();

What confuses me is where the variable post and user came from? I see in this line ...

connection.Query<Post, User, Post>

that Post and User are the models and I understand that ..

(post, user) => { post.Owner = user; return post;}

is a function that defines the mapping, but where do post and user get instantiated?

Upvotes: 0

Views: 114

Answers (1)

SomeoneLost
SomeoneLost

Reputation: 226

Its a Lambda function. Don't know the technical explanation, but basically connection.Query returns multiple records, each containing a post and user as per the query. With (post, user) => you're declaring that post will represent the Post and user will represent the User from each record.

Upvotes: 1

Related Questions