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

编程入门 行业动态 更新时间:2024-10-13 04:24:21
本文介绍了如何在 EF Core 中调用 ThenInclude 两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I'm creating an ASP.NET Core API app, and relying on EF Core. I have entities defined like this:

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

其中 Comment 和 Like 是其他一些实体.请注意,为简洁起见,我简化了实体.然后,我想获取用户的 Posts,但还要包括帖子获得的 Likes 和 Comments.所以,我做了这样的事情:

Where Comment and Like are some other entities. Please note that I have simplified the entities for brevity. Then, I want to get the Posts of a user, but also include the Likes and Comments that a post has gotten. So, I did something like this:

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?

推荐答案

您不能将 ThenInclude 与多个导航属性一起使用.你必须有Include.

You cannot use ThenInclude with multiple navigation properties. You have to have Include.

这是为此打开的错误.

更多推荐

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

本文发布于:2023-11-13 22:53:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1585541.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两次   如何在   Core   EF   ThenInclude

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!