c# - 在 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: 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

怎么了,我应该怎么办?

最佳答案

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

关于c# - 在 Entity Framework Core 中包含集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36601227/

相关文章:

.net - EF Core 一对多关系 : ICollection or Hashset?

code-generation - 是否有用于跨平台 asp.net 5 开发的 T4 模板和 EnvDTE 的替代方案?

javascript - 建立一个包含模型的链接

c# - 在 Entity Framework 中测试 View 模型

entity-framework - 如何修复 "EntityMemberChanged was called without first calling EntityMemberChanging"

c# - 从生成的表中检索数据时对象名称 'dbo.TableName' 无效

c# - 在 iTextSharp 中,我们可以设置 pdfwriter 的垂直位置吗?

c# - TCP C 套接字服务器到 C# 客户端,数据包一起使用发送

entity-framework - 将未更改的项目添加到充满已添加项目的对象图中

c# - 在 MySql.Data.EntityFrameworkCore 中找不到 Database SetInitializer