gpt4 book ai didi

c# - "Include"在 Entity Framework Core 中 SelectMany + Select 后不工作

转载 作者:行者123 更新时间:2023-11-30 14:22:57 27 4
gpt4 key购买 nike

我使用 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; }
}

我需要做什么才能使翻译在返回的可查询中加载?

最佳答案

这是 Loading Related Data - Ignored includes 中描述的当前 EF Core 限制:

If you change the query so that it no longer returns instances of the entity type that the query began with, then the include operators are ignored.

据此,你需要从context.Set<TitleInformation>()开始查询.但是为了产生所需的过滤,您需要来自 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));

或者,如果TitleInformation之间的关系和 Book是一对多的(上面是一对一的):

class TitleInformation
{
// ...
public List<Book> Books { get; set; }
}

分别是:

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));

关于c# - "Include"在 Entity Framework Core 中 SelectMany + Select 后不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47529270/

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