gpt4 book ai didi

c# - 在 Entity Framework Core 中包含集合

转载 作者:IT王子 更新时间:2023-10-29 04:26:41 25 4
gpt4 key购买 nike

例如,我有那些实体:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com