在Entity Framework Core中包含集合

Yur*_* N. 23 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; }
}
Run Code Online (Sandbox Code Playgroud)

如果我只知道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();
}
Run Code Online (Sandbox Code Playgroud)

但问题是,它会抛出异常

ArgumentException:属性表达式'x => {from page y in x select [y] .PageTitle}'无效.表达式应表示属性访问:'t => t.MyProperty'.指定多个属性时,请使用匿名类型:'t => new {t.MyProperty1,t.MyProperty2}'.参数名称:propertyAccessExpression

怎么了,我该怎么办?

dii*_*___ 44

尝试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();
}
Run Code Online (Sandbox Code Playgroud)

  • 它是如何工作的?我的意思是,当我输入y.PageTitle时,我没有PageTitle的Intellisense字段,但它有效,构建! (13认同)
  • @YuriyN.这是因为你使用了这个重载:`ThenInclude <TEntity,TPreviousProperty,TProperty>([NotNullAttribute]这个IIncludableQueryable <TEntity,TPreviousProperty> source,[NotNullAttribute] Expression <Func <TPreviousProperty,TProperty >> navigationPropertyPath)`.VS intellisense看到另一个是`ThenInclude <TEntity,TPreviousProperty,TProperty>([NotNullAttribute]这个IIncludableQueryable <TEntity,`**IEnumerable <TPreviousProperty>**`> source,[NotNullAttribute] Expression <Func <TPreviousProperty,TProperty> > navigationPropertyPath)` (3认同)