Search code examples
c#entity-frameworkentity-framework-coreeager-loading

Loading multiple levels of related data in Entity Framework Core not working as expected


I want to eagerly load some data related to an Article object.

return await context.Articles
    .Include(x => x.ArticleTags)
        .ThenInclude(x => x.Tag)
            // .ThenInclude(x => x.Value)
    .Include(x => x.Author)
        .ThenInclude(x => x.UserInfo)
    .Include(x => x.Approver)
        .ThenInclude(x => x.UserInfo)
    .Include(x => x.Rejecter)
        .ThenInclude(x => x.UserInfo)
    .Include(x => x.LinkSubmitter)
        .ThenInclude(x => x.UserInfo)
    .FirstOrDefaultAsync(x => x.Id == id);

In this article object, all of the displayed properties can be null or empty. e.g. no tags, no author, no approver .. etc.

The query works as is (with the commented out line).

However, if I include the nested ThenInclude(), it fails with an error:

System.ArgumentNullException: Value cannot be null. Parameter name: source

I believe the reason for this is because the article has no tags and It's trying to eagerly load the value of tags that don't exist. How would I eagerly load all tag data which may or may not exist for the article?


Solution

  • Try .Include(x => x.ArticleTags.Tag?.Value)