如何使用自动查询返回多对多关系的嵌套对象

时间:2019-06-19 19:15:19

标签: servicestack

让我说我有3个班级:

public class Book
{
    [Autoincrement]
    public int Id {get; set;}
    public string Title {get; set;}
    [Reference]
    public list<BookAuthor> BookAuthors {get; set;}
}

public class BookAuthor
{
    [ForeignKey(typeof(Book))]
    public int BookId {get; set;}
    [Reference]
    public Book Book {get; set;}

    [ForeignKey(typeof(Author))]
    public int AuthorId {get; set;}
    [Reference]
    public Author Author {get; set;}
}

public class Author
{
    [Autoincrement]
    public int Id {get; set;}
    public string Name {get; set;}
}

书籍和作者之间存在多对多的关系。

这是我当前正在构建的应用程序的常见问题,我需要在前端提供这样的DTO:

public class BookDto
{
    public int Id {get; set;}
    public string Title {get; set;}
    public list<Author> Authors {get; set;}
}

前端需要嵌入Author。我需要一种在单个查询中将Authors嵌套在DTO中的方法。

这可能吗?

1 个答案:

答案 0 :(得分:1)

我添加了一个实时示例来完成您想要的操作you can play with on Gistlyn

在OrmLite中,每个数据模型类均与基础表进行1:1映射,并且对M:M查询没有神奇的支持,因此必须将它们用作与RDBMS中存储的表不同的表。

每个表还需要在OrmLite中添加一个唯一的主ID(在我已添加的BookAuthor中丢失,我还添加了一个[UniqueConstraint]以强制执行没有重复的关系,这些更改导致类看起来像:

public class Book
{
    [AutoIncrement]
    public int Id {get; set;}
    public string Title {get; set;}
    [Reference] 
    public List<BookAuthor> BookAuthors {get; set;}
}

[UniqueConstraint(nameof(BookId), nameof(AuthorId))]
public class BookAuthor
{
    [AutoIncrement] public int Id {get; set;} 

    [ForeignKey(typeof(Book))]
    public int BookId {get; set;}

    [ForeignKey(typeof(Author))]
    public int AuthorId {get; set;}
}

public class Author
{
    [AutoIncrement]
    public int Id {get; set;}
    public string Name {get; set;}
}

public class BookDto
{
    public int Id { get; set; }
    public string Title { get; set; }
    public List<Author> Authors { get; set; }
}

然后创建表并添加一些示例数据:

db.CreateTable<Book>();
db.CreateTable<Author>();
db.CreateTable<BookAuthor>();

var book1Id = db.Insert(new Book { Title = "Book 1" }, selectIdentity:true);
var book2Id = db.Insert(new Book { Title = "Book 2" }, selectIdentity:true);
var book3Id = db.Insert(new Book { Title = "Book 3" }, selectIdentity:true);

var authorAId = db.Insert(new Author { Name = "Author A" }, selectIdentity:true);
var authorBId = db.Insert(new Author { Name = "Author B" }, selectIdentity:true);

db.Insert(new BookAuthor { BookId = 1, AuthorId = 1 });
db.Insert(new BookAuthor { BookId = 1, AuthorId = 2 });
db.Insert(new BookAuthor { BookId = 2, AuthorId = 2 });
db.Insert(new BookAuthor { BookId = 3, AuthorId = 2 });

然后在OrmLite中的单个查询中选择多个表,您可以使用SelectMulti,例如:

var q = db.From<Book>()
    .Join<BookAuthor>()
    .Join<BookAuthor,Author>()
    .Select<Book,Author>((b,a) => new { b, a });
var results = db.SelectMulti<Book,Author>(q);

由于属性名称follows the reference conventions的连接不需要显式指定,因为可以隐式地推断它们。

这将返回一个List<Tuple<Book,Author>>,然后您可以使用字典将所有作者和他们的书缝合在一起:

var booksMap = new Dictionary<int,BookDto>();
results.Each(t => {
    if (!booksMap.TryGetValue(t.Item1.Id, out var dto))
        booksMap[t.Item1.Id] = dto = t.Item1.ConvertTo<BookDto>();        
    if (dto.Authors == null) 
        dto.Authors = new List<Author>();
    dto.Authors.Add(t.Item2);
});

我们可以从字典值中获取书籍列表:

var dtos = booksMap.Values;
dtos.PrintDump();

在其中填充有作者的书籍并打印出来:

[
    {
        Id: 1,
        Title: Book 1,
        Authors: 
        [
            {
                Id: 1,
                Name: Author A
            },
            {
                Id: 2,
                Name: Author B
            }
        ]
    },
    {
        Id: 2,
        Title: Book 2,
        Authors: 
        [
            {
                Id: 2,
                Name: Author B
            }
        ]
    },
    {
        Id: 3,
        Title: Book 3,
        Authors: 
        [
            {
                Id: 2,
                Name: Author B
            }
        ]
    }
]

自动查询

AutoQuery只能实现可以自动执行的隐式查询,如果您需要执行任何自定义查询或投影,则需要提供custom AutoQuery implementation,因为可以隐式地推断联接,因此您可能可以让AutoQuery构造合并的查询,因此您只需要提供自定义Select()投影和自己映射即可,例如:

[Route("/books/query")]
public class QueryBooks : QueryDb<Book,BookDto>, 
    IJoin<Book,BookAuthor>,
    IJoin<BookAuthor,Author> {}

public class MyQueryServices : Service
{
    public IAutoQueryDb AutoQuery { get; set; }

    //Override with custom implementation
    public object Any(QueryBooks query)
    {
        var q = AutoQuery.CreateQuery(query, base.Request)
            .Select<Book,Author>((b,a) => new { b, a });
        var results = db.SelectMulti<Book,Author>(q);

        var booksMap = new Dictionary<int,BookDto>();
        results.Each(t => {
            if (!booksMap.TryGetValue(t.Item1.Id, out var dto))
                booksMap[t.Item1.Id] = dto = t.Item1.ConvertTo<BookDto>();        
            if (dto.Authors == null) 
                dto.Authors = new List<Author>();
            dto.Authors.Add(t.Item2);
        });
        return new QueryResponse<BookDto> { Results = booksMap.Values.ToList() };
    }
}