如何在EF Core中两次调用ThenInclude? [英] How to call ThenInclude twice in EF Core?
问题描述
我正在创建一个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>();
}
其中评论
和喜欢
是其他一些实体。请注意,为简洁起见,我简化了实体。然后,我想获取用户的帖子
,还包括喜欢 c和
发表评论的评论
。因此,我做了这样的事情:
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!