For example, I have those entities:
public class Book { [Key] public string BookId { get; set; } public List<BookPage> Pages { get; set; } public string Text { get; set; } } public class BookPage { [Key] public string BookPageId { get; set; } public PageTitle PageTitle { get; set; } public int Number { get; set; } } public class PageTitle { [Key] public string PageTitleId { get; set; } public string Title { get; set; } }
How should I load all PageTitles, if I know only the BookId?
Here it is how I'm trying to do this:
using (var dbContext = new BookContext()) { var bookPages = dbContext .Book .Include(x => x.Pages) .ThenInclude(x => x.Select(y => y.PageTitle)) .SingleOrDefault(x => x.BookId == "some example id") .Pages .Select(x => x.PageTitle) .ToList(); }
But the problem is, that it throws exception
ArgumentException: The properties expression 'x => {from Pages y in x select [y].PageTitle}' is not valid. The expression should represent a property access: 't => t.MyProperty'. When specifying multiple properties use an anonymous type: 't => new { t.MyProperty1, t.MyProperty2 }'. Parameter name: propertyAccessExpression
What's wrong, what exactly should I do?
The Entity Framework Core (EF) extension method Include provides us the ability to load additional data besides the entities we are querying for. For example: loading products along with their translations. var products = Context. Products . Include(p => p.
To include both, you need to specify each include path starting at the root. For example, Blog -> Posts -> Author and Blog -> Posts -> Tags . It doesn't mean you'll get redundant joins; in most cases, EF will combine the joins when generating SQL. You can also load multiple navigations using a single Include method.
Entity Framework Classic ThenIncludeThe ThenInclude method moves the chaining level to the property included. It allows us to include related objects from the next level. ThenInclude is a syntactic sugar method to make it easier and clearer to include multiple related objects.
Entity Framework Classic Include The Include method lets you add related entities to the query result. In EF Classic, the Include method no longer returns an IQueryable but instead an IncludeDbQuery that allows you to chain multiple related objects to the query result by using the AlsoInclude and ThenInclude methods.
Try accessing PageTitle
directly in ThenInclude
:
using (var dbContext = new BookContext()) { var bookPages = dbContext .Book .Include(x => x.Pages) .ThenInclude(y => y.PageTitle) .SingleOrDefault(x => x.BookId == "some example id") .Select(x => x.Pages) .Select(x => x.PageTitle) .ToList(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With