在Entity Framework Core中包含集合

31
例如,我有以下实体:
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 Pages y in x select [y].PageTitle}' 是无效的。表达式应该代表属性访问:'t => t.MyProperty'。当指定多个属性时,请使用匿名类型:'t => new { t.MyProperty1, t.MyProperty2 }'。参数名称:propertyAccessExpression

出了什么问题,我应该怎么做?

1个回答

54
尝试直接访问 ThenInclude 中的 PageTitle:
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();
}

14
它是如何工作的?我的意思是,当我输入y.PageTitle时,我没有PageTitle的Intellisense字段,但它仍然能够正常工作和构建! - Yurii N.
5
@YuriyN,这是因为您使用了此重载:ThenInclude<TEntity, TPreviousProperty, TProperty>([NotNullAttribute] this IIncludableQueryable<TEntity, TPreviousProperty> source, [NotNullAttribute] Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath)。VS智能感知看到的是另一个重载,即ThenInclude<TEntity, TPreviousProperty, TProperty>([NotNullAttribute] this IIncludableQueryable<TEntity, IEnumerable<TPreviousProperty>> source, [NotNullAttribute] Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath)。请注意,我已经将代码中的可空和非空属性注释删除,以便更好地理解内容。 - yakya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接