在Entity Framework Core中包含集合

c# entity-framework entity-framework-core

例如,我有這些實體:

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

如果我只知道BookId,我應該如何加載所有PageTitles?

這是我試圖這樣做的方式:

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

但問題是,它會拋出異常

ArgumentException:屬性表達式'x => {from page y in x select [y] .PageTitle}'無效。表達式應表示屬性訪問:'t => t.MyProperty'。指定多個屬性時,請使用匿名類型:'t => new {t.MyProperty1,t.MyProperty2}'。參數名稱:propertyAccessExpression

怎麼了,我該怎麼辦?

一般承認的答案

嘗試訪問PageTitle直接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();
}


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因