Given this test:
public class Author
{
public int AuthorId { get; set; }
public List<Book> Books { get; set; } = new List<Book>();
}
public class Book
{
public int BookId { get; set; }
}
[Fact]
public async Task DapperCollapseLeftJoin()
{
var sql = @" select 1 as AuthorId, 1 as BookId
union select 1 as AuthorId, 2 as BookId
union select 2 as AuthorId, 3 as BookId
union select 2 as AuthorId, 4 as BookId";
var authorsWithBooks =
(await AC.OpenConnection.QueryAsync<Author, Book, Author>(sql,
(author, book) => { author.Books.Add(book); return author; },
splitOn: "AuthorId, BookId")).ToList();
// fails because we're getting 4 author+book rows
Assert.Equal(2, authorsWithBooks.Count);
}
The documentation for Dapper says multimapping maps rows to multiple objects and doesn't mention anything about actually collapsing objects (like would happen for left/inner joins where leftmost column values repeat).
Is there a Dapper-native way to make this happen?
There is not currently an inbuilt mechanism for doing this flattening, but there is an example in the test suite here. It isn't hugely pretty, and this is something I'd like to make better support for, but it has never reached the top of the list of things to do.