我刚刚从PetaPoco转到Dapper,我试图找到一个如何在Dapper中实现一对多关系的例子。在PetaPoco中,您可以执行以下操作。这很好,因为实现作者所需的所有逻辑都包含在一个类中。示例来自PetaPoco - Mapping One-to-Many and Many-to-One Relationships
public class AuthorPostRelator
{
private author current;
public author Map(author a, post p)
{
// Terminating call. Since we can return null from this function
// we need to be ready for PetaPoco to callback later with null
// parameters
if (a == null)
return current;
// Is this the same author as the current one we're processing
if (current != null && current.id == a.id)
{
// Yes, just add this post to the current author's collection of posts
current.posts.Add(p);
// Return null to indicate we're not done with this author yet
return null;
}
// This is a different author to the current one, or this is the
// first time through and we don't have an author yet
// Save the current author
var prev = current;
// Setup the new current author
current = a;
current.posts = new List<post>();
current.posts.Add(p);
// Return the now populated previous author (or null if first time through)
return prev;
}
}
// use the AuthorPostRelator to materialize the returned Author objects.
var authors = db.Fetch<author, post, author>(new AuthorPostRelator().Map,
"SELECT * FROM authors LEFT JOIN posts ON posts.author = authors.id ORDER BY posts.id");