简体   繁体   中英

Issue regarding Entity Framework Core eager loading an item inside of .Include

Here is my situation. I have Posts and Comments. When I do my query to get posts I write it like this:

var queryable = _dataContext.Post
                    .Where(x => x.DateCreated <= initialDateOfPageLoad)
                    .AsQueryable();

var posts = await queryable
                .Include(p => p.User)
                .Include(c => c.Comments) // ***
                .Include(l => l.Likes)
                .OrderByDescending(p => p.DateCreated)
                .ToListAsync();

Now the comments entity has an Eagerly loaded User.

public class Comment
{
    public int Id { get; set; }
    public int PostId { get; set; }
    public Post Post { get; set; }
    public Guid UserId { get; set; }
    public User User { get; set; } // ***
    public string Body { get; set; }
    public bool Modified { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime? DateModified { get; set; }
}

Whenever I get my posts back I map the comments into a dto like this:

public class CommentDto
{
    public int Id { get; set; }
    public string Body { get; set; }
    public DateTime DateCreated { get; set; }
    public Guid UserId { get; set; }
    public int PostId { get; set; }
    public string DisplayName { get; set; } // ***
    public string ImagePath { get; set; } // ***
}

So I need the User that should be eagerly loaded with the comment to insert the UserId and ImagePath that is available on the User Entity.

Now the weird thing is, the user for the comment is only eagerly loaded when that user has made a post...

If I try to comment with a user that hasn't made a post I will get null values and when I debug it shows the User as not being loaded. But once that user makes a post (which is unrelated to the post the user comments on) then everything is eagerly loaded properly with the comment.

Can someone please explain what is going on here? I don't expect every user to make a post, but I would expect them to comment. Why isn't the eager loading working in this scenario?

You aren't eagerly loading the users for the comments, but if they made a post, then it is auto fixing it up for you.

Add .Include(p => p.Comments).ThenInclude(c => c.User) to your query to fix it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM