C# 在实体框架核心中选择多个+选择后包括不工作
我使用EntityFrameworkCoreV2进行了这个查询,但是Include/thenclude没有像我预期的那样工作。以下是查询:C# 在实体框架核心中选择多个+选择后包括不工作,c#,entity-framework,entity-framework-core,iqueryable,C#,Entity Framework,Entity Framework Core,Iqueryable,我使用EntityFrameworkCoreV2进行了这个查询,但是Include/thenclude没有像我预期的那样工作。以下是查询: var titlesOwnedByUser = context.Users .Where(u => u.UserId == userId) .SelectMany(u => u.OwnedBooks) .Select(b =>
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; }
}
要在返回的查询中加载翻译,我必须做些什么?这是当前的EF核心限制,如中所述: 如果更改查询,使其不再返回查询开始时的实体类型的实例,则会忽略include运算符 因此,您需要从context.Set启动查询。但为了生成所需的过滤,您需要从TitleInformation到Book的反向导航属性,该属性当前在您的模型中缺失:
class TitleInformation
{
// ...
public Book Book { get; set; } // add this and map it properly with fluent API
}
一旦你有了它,你可以用这样的东西:
var titlesOwnedByUser = context.Set<TitleInformation>()
.Include(ti => ti.Title)
.ThenInclude(n => n.Translations)
.Where(ti => ti.Book.Owners.Any(bu => bu.UserId == userId));
分别为:
var titlesOwnedByUser = context.Set<TitleInformation>()
.Include(ti => ti.Title)
.ThenInclude(n => n.Translations)
.Where(ti => ti.Books.SelectMany(b => b.Owners).Any(bu => bu.UserId == userId));
你能显示实体的配置吗?听起来像。您应该从context.TitleInformation开始以其他方式构建查询。@H.Herzl请检查更新操作。@IvanStoev我怎么知道如何开始?你能把代码写进去吗?我有点迷路了:可能是重复的
var titlesOwnedByUser = context.Set<TitleInformation>()
.Include(ti => ti.Title)
.ThenInclude(n => n.Translations)
.Where(ti => ti.Books.SelectMany(b => b.Owners).Any(bu => bu.UserId == userId));