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

c# eager-loading entity-framework entity-framework-core

Question

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?

1
0
12/22/2016 7:36:07 AM

Accepted Answer

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

-1
12/22/2016 7:24:48 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow