简体   繁体   中英

EF: Load related entities in second request

To explain the situation I will provide dummy code bellow

public class Author
{
     public int AuthorId { get; set; }
     public virtual ICollection<Book> Books { get; set; }
}

public class Book
{
     public int BookId { get; set; }
     public virtual Author Author { get; set; }    
}

var authors = context.Authors.ToList();     (1)
context.Books.Load();                       (2)
var firstAuthorBook = authors.First().Book; (3)

(1) I load all authors from db.I do it without eager loading so I know that related books won't be loaded. (2) I load all books separately using Explicit Loading

(3) I try to get first author book . But here the lazy load call to db happened . Why It happened?Why ef need one more call to db if the all entities were loaded in (2) ?

How EF is going to understand that you want to load first author's books from in memory collection. By default it will reach out to db for getting books due to lazy-loading.

You should be explicitly loading related books like this:

var firstAuthor = authors.First();
context.Entry(firstAuthor)
       .Collection(a => a.Books)
       .Load();

Then access firstAuthor.Books

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM