如何在 Entity Framework Code First 中急切地包含实体的子元素和孙元素?
想象一下三个相关的实体(客户、书籍、作者),如下所示:
客户有很多本书
一本书有一个作者
我使用该数据打印如下报告:
Customer: Peter
Book: To Kill a Mockingbird - Author: Harper Lee
Book: A Tale of Two Cities - Author: Charles Dickens
Customer: Melanie
Book: The Hobbit - Author: J. R. R. Tolkien
当我查询客户时,如预期的那样,我得到了一堆查询具有以下性质
- 获取客户的查询
- 每个客户获取其书籍的查询
- 每本书获取其作者的查询
我可以通过包含书籍来减少查询数量,如下所示:
varcustomers = db.Customers.Include(c => c.书籍);
但我不知道如何加载第三层(作者)。我怎样才能做到这一点?
Imagine three entities (Customer, Book, Author) related like this:
A Customer has many Books
A Book has one Author
I use that data to print a report like this:
Customer: Peter
Book: To Kill a Mockingbird - Author: Harper Lee
Book: A Tale of Two Cities - Author: Charles Dickens
Customer: Melanie
Book: The Hobbit - Author: J. R. R. Tolkien
When I query for Customers I get, as expected, a bunch of queries of the following nature
- A query to get the Customers
- A query per Customer to get his Books
- A query per Book to get its author
I can reduce the number of queries by including the books like so:
var customers = db.Customers.Include(c => c.Books);
But I don't know how to load the third level (Author). How can I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
此外,没有必要使用字符串重载。此方法也适用:
有关更多示例,请参阅 EF 团队博客文章:
本教程:
http://www.asp.net/entity-framework/tutorials/reading-lated-data-with-the-entity-framework-in-an-asp-net-mvc-application
Also, it isn't necessary to use the string overload. This method will work too:
For more examples see the EF team blog post:
http://blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature-ctp5-part-6-loading-related-entities.aspx
And this tutorial:
http://www.asp.net/entity-framework/tutorials/reading-related-data-with-the-entity-framework-in-an-asp-net-mvc-application
Include
有一个重载,它接受一个字符串,该字符串可以表示您需要的任何额外属性的完整路径:它看起来很奇怪,因为“Author”不是书籍集合上的属性(而是一个属性)在每本书上)但它有效。试一试。
There's an overload for
Include
that accepts a string which can denote the full path to any extra properties you need:It looks strange because "Author" isn't a property on a collection of books (rather a property on each individual book) but it works. Give it a whirl.
您可以使用
ThenInclude
关键字:varcustomers = db.Customers.Include(c => c.Books).ThenInclude(book => book.Author));}
You can use
ThenInclude
keyword:var customers = db.Customers.Include(c => c.Books).ThenInclude(book => book.Author));}