PetaPoco和多对一,一对多和多对多的关系

Rob*_*nik 5 relational-database petapoco

PetaPoco已经以实验形式引入了多POCO查询(目前).正如他们的博客文章所建议的那样,并且它提供的代码看起来很好,并且当我们每行加载多个POCO时,只要它们不重复记录,所有这些都是一对一的关系.

当至少一方有很多关系时会发生什么?实际上,示例代码是多对一关系数据.

示例代码显然是多对一关系.我没有测试任何PetaPoco代码,但博客文章中提供的代码是做什么的?是否每个Article都有自己的User对象实例,即使某些用户可能是同一个用户,或者他们共享同一个用户对象实例?

那么其他许多关系类型呢?他们如何工作?

Sch*_*ime 7

通常我会自己映射这些一对多查询,如下例所示.

[TableName("Blogs"), PrimaryKey("BlogId")]
public class Blog {
    public int BlogId {get;set;}
    public string Title {get;set;}

    [Ignore]
    public IList<Post> Posts {get;set;}
}

[TableName("Posts"), PrimaryKey("PostId")]
public class Post {
    public int PostId {get;set;}
    public int BlogId {get;set;}
    public string Subject {get;set;}
    public string Content {get;set;}
}

public class FlatBlogPost {
    public int BlogId {get;set;}
    public string Title {get;set;}
    public int PostId {get;set;}
    public string Subject {get;set;}
    public string Content {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

我可以通过两种方式显示一个博客的帖子列表,或者没有太多工作,所有博客.

1.两个查询 -

var Blog = Db.Query<Blog>(1);  
var Posts = Db.Query<Post>("where BlogId = @0", 1);
Run Code Online (Sandbox Code Playgroud)

2.One query =

var flat = Db.Query<FlatBlogPost>("select b.blogid, b.title, p.postid, p.subject, 
           p.content from blogs b inner join posts p on b.blogid = p.blogid where
           b.blogid = @0", 1);

var blog = flat
    .GroupBy(x=> new { x.BlogId, x.Title })
    .Select(x=> new Blog {
        BlogId = x.Key.BlogId,
        Title = x.Key.Title,
        Posts = x.Select(y=> new Post{
                    PostId = y.PostId,
                    BlogId = x.Key.BlogId,
                    Subject = y.Subject,
                    Content = y.Content
                }).ToList()
    });
Run Code Online (Sandbox Code Playgroud)

但是通常在数字2中我会直接从FlatBlogPost对象映射到我需要显示数据的viewmodel.

更新
查看扩展PetaPoco的这些帮助程序,以支持基本的一对多和多对一查询.schotime.net/blog/index.php/2011/08/21/petapoco-one-to-many-and-many-to-one/ https://schotime.wordpress.com/2011/08/21/petapoco-一个一对多和多对多到一/