gpt4 book ai didi

c# - 如何在 EF Core 中调用 ThenInclude 两次?

转载 作者:行者123 更新时间:2023-12-03 03:26:20 28 4
gpt4 key购买 nike

我正在创建一个 ASP.NET Core API 应用程序,并依赖于 EF Core。我有这样定义的实体:

public class AppUser : IdentityUser
{
public string FirstName { get; set; }

public string LastName { get; set; }

[InverseProperty(nameof(Post.Author))]
public ICollection<Post> Posts { get; set; } = new List<Post>();
}

public class Post
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

public string AuthorId { get; set; }

[ForeignKey("AuthorId")]
public virtual AppUser Author { get; set; }

[InverseProperty(nameof(Like.Post))]
public ICollection<Like> Likes { get; set; } = new List<Like>();

[InverseProperty(nameof(Comment.Post))]
public ICollection<Comment> Comments { get; set; } = new List<Comment>();
}

在哪里 CommentLike是其他一些实体。请注意,为简洁起见,我已经简化了实体。然后,我想得到 Posts用户,但也包括 LikesComments一个帖子得到了。所以,我做了这样的事情:
return _context.Users
.Include(u => u.Location)
.Include(u => u.Posts)
.ThenInclude(p => p.Comments)
.ThenInclude(c => c.Owner)
.Include(u => u.Posts)
.ThenInclude(p => p.Likes)
.ThenInclude(l => l.Giver)
.Where(u => u.Id == userId)
.FirstOrDefault();

现在,这工作正常,但如您所见,我正在调用 .Include(u = u.Posts)两次。有没有办法调用 ThenInclude在同一属性上两次,实际上没有写 Include声明还两次?

最佳答案

Now, this works fine, but as you can see I'm calling .Include(u = u.Posts) twice. Is there a way to call ThenInclude twice on same property, without actually writing the Include statement also twice?



调用 Include(u => u.Posts)两次是正确的方法。

来自 EF Core docs ...强调最后一句话。

You may want to include multiple related entities for one of the entities that is being included. For example, when querying Blogs, you include Posts and then want to include both the Author and Tags of the Posts. To do this, you need to specify each include path starting at the root. For example, Blog -> Posts -> Author and Blog -> Posts -> Tags. This does not mean you will get redundant joins, in most cases EF will consolidate the joins when generating SQL.


using (var context = new BloggingContext())
{
var blogs = context.Blogs
.Include(blog => blog.Posts)
.ThenInclude(post => post.Author)
.Include(blog => blog.Posts)
.ThenInclude(post => post.Tags)
.ToList();
}

关于c# - 如何在 EF Core 中调用 ThenInclude 两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50897638/

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