我有一个使用Entity Framework Core (v2)的查询,但是Include
/ThenInclude
不像我预期的那样工作。以下是查询:
var titlesOwnedByUser = context.Users
.Where(u => u.UserId == userId)
.SelectMany(u => u.OwnedBooks)
.Select(b => b.TitleInformation)
.Include(ti => ti.Title)
.ThenInclude(n => n.Translations);
这个查询是有效的,但我得到的标题是 null
。
为了澄清,这些类是这些
class User
{
public int Id { get; set; }
public List<BookUser> OwnedBooks { get; set; }
}
class Book
{
public int Id { get; set; }
public TitleInformation TitleInformation { get; set; }
public List<BookUser> Owners { get; set; }
}
class BookUser
{
public int BookId { get; set; }
public int UserId { get; set; }
public Book Book { get; set; }
public User User { get; set; }
}
class MyContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<BookUser>()
.HasOne(x => x.User)
.WithMany(x => x.OwnedBooks)
.HasForeignKey(x => x.UserId);
modelBuilder.Entity<BookUser>()
.HasOne(x => x.Book)
.WithMany(x => x.Owners)
.HasForeignKey(x => x.BookId);
}
}
class TitleInformation
{
public int Id { get; set; }
public Title Title { get; set; }
public Title Subtitle { get; set; }
}
class Title
{
public int Id { get; set; }
public string OriginalTitle { get; set; }
public List<Translation> Translations { get; set; }
}
我需要做什么才能使翻译在返回的可查询结果中加载?
context.TitleInformation
开始构建查询,换个方式来做。 - Ivan Stoev