例如,我有以下实体:
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
出了什么问题,我应该怎么做?
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