Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

c# - How to call ThenInclude twice in 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>();
}

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

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?

question from:https://stackoverflow.com/questions/66060516/ef-core-linq-include-multiple-sub-properties

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Here is bug opened for this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...