如何热切地将实体的子孙元素包括在实体框架代码中? [英] How do I eagerly Include the child and grandchild elements of an entity in Entity Framework Code First?

查看:93
本文介绍了如何热切地将实体的子孙元素包括在实体框架代码中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下这三个实体(客户,书籍,作者)相关:

Imagine three entities (Customer, Book, Author) related like this:

客户有很多图书

一本书有一个作者

我使用这些数据打印如下报告:

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


  1. 查询以获取客户

  2. 查询每个客户获取他的书籍

  3. 每本书查询以获取作者

我可以通过包含这些书籍来减少查询数量:

I can reduce the number of queries by including the books like so:

var customers = db.Customers.Include(c => c.Books);

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?

推荐答案

包含接受可以表示您需要的任何额外属性的完整路径的字符串:

There's an overload for Include that accepts a string which can denote the full path to any extra properties you need:

var customers = db.Customers.Include("Books.Author");

看起来很奇怪,因为作者不是书籍集合(而是属性)的属性在每本书上),但它的作品。给它一个旋转。

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.

这篇关于如何热切地将实体的子孙元素包括在实体框架代码中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆