简体   繁体   中英

Include collection in Entity Framework Core

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?

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();
}

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