Select Post Tags with Dapper dot net

c# dapper orm sql sql-server

Question

I have three tables in my database. Post,Tag and PostTag. Tag and Post tables has Many To Many relation and because of that PostTag table created.

My question is how can i select all posts in my table with its tags and map result to my POCO entity with Dapper.net.

Here is my poco classes. Post:

public class Post
{
    public long Id { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }

    public virtual ICollection<Tag> Tags { get; set; }
}

Tag:

public class Tag
{
    public long Id { get; set; }
    public string Title { get; set; }

    public virtual ICollection<Post> Posts { get; set; }
}

I want to select all posts with all related tags to each post. I want to know how can i get a result like this ef query: _context.Posts.Include(x => x.Tags).ToList()

Popular Answer

Dapper is just an object mapping library, and you would have to write raw SQL or Stored Procedures by yourself. For example:

var sql = 
@"
select Id, Title, Body from Post where Id = @id
select Id, Title from Tag t join PostTag pt on pt.TagId = p.Id where pt.PostId = @id";

using (var multi = connection.QueryMultiple(sql, new {id=postId}))
{
   var post = multi.Read<Post>().Single();
   var tags= multi.Read<Tag>().ToList();
   post.Tags = tags;
} 

And similarly with mapping posts to tags.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why