使用LINQ进行双嵌套OData收集[英] Use LINQ for double-nested OData collection

本文是小编为大家收集整理的关于使用LINQ进行双嵌套OData收集的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我有一个用于书籍的自定义 OData 提要.每本书可以有多个作者,一个作者可以参与多本书,所以我使用连接表(Book - BookAuthorJoin - Author)实现了这一点.我的代理对象有 Book.BookAuthorJoins BookAuthorJoin.Books &BookAuthorJoin.Authors.

我想要做的是有一个单一的查询,我在一个 LINQ 查询中获取作者的所有书籍,但在应用过滤器时遇到了问题.似乎我想要两个 Expand() 方法,但这不起作用.以下查询不起作用,但显示了我正在尝试做的事情:

var query = from book in ODataContext.Books.Expand("BookAuthorJoins").Expand("Authors")
            where book.BookAuthorJoins.Author.AuthorID = authorID
            select book;

推荐答案

在服务器端,一对多或多对多的关系通常只暴露为一个导航属性,在中间会让你的生活更加艰难.如果您使用 EF,您应该能够隐藏表格并将关系公开为导航属性.无论如何,要获取某个作者的所有书籍,查询应该如下所示:

/Authors(123)/Books

此查询的结果只是书籍的提要.

如果你确实暴露了连接表,那么类似这样的工作:

/Authors(123)/BookAuthorJoins?$expand=Book

但是这次你也得到了所有 BookAuthorJoin 和 Book.

本文地址:https://www.itbaoku.cn/post/1556933.html

问题描述

I've got a custom OData feed that for books. Each book can have multiple authors and an author can be involved in multiple books so I implemented this using a join table (Book - BookAuthorJoin - Author). My proxy object has Book.BookAuthorJoins BookAuthorJoin.Books & BookAuthorJoin.Authors.

What I want todo is have a single query where I get all the books for an author in a single LINQ query, but having trouble applying the filter. Seems I want two Expand() methods, but that isn't working. The following query doesn't work, but shows what I'm trying to do:

var query = from book in ODataContext.Books.Expand("BookAuthorJoins").Expand("Authors")
            where book.BookAuthorJoins.Author.AuthorID = authorID
            select book;

推荐答案

On the server side, the 1-to-many or many-to-many relationship is usually exposed as just a navigation property, exposing the join table in the middle will make your life much harder. If you use EF you should be able to hide the table and just expose the relationship as a navigation property. In any case, to get all books for a certain author the query should look like:

/Authors(123)/Books

The result of this query is just a feed of books.

If you do keep the join table exposed then something like this migth work:

/Authors(123)/BookAuthorJoins?$expand=Book

But this time you get all the BookAuthorJoins with the Book for each as well.