How do I eagerly Include the child and grandchild elements of an entity in Entity Framework Code First?

前端 未结 3 1863
故里飘歌
故里飘歌 2020-12-05 12:48

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

相关标签:
3条回答
  • 2020-12-05 13:03

    You can use ThenInclude keyword:

    var customers = db.Customers.Include(c => c.Books).ThenInclude(book => book.Author));}

    0 讨论(0)
  • 2020-12-05 13:05

    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.

    0 讨论(0)
  • 2020-12-05 13:12

    Also, it isn't necessary to use the string overload. This method will work too:

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

    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

    0 讨论(0)
提交回复
热议问题