Exception when trying to use `ThenInclude` in EF Core

.net .net-core c# entity-framework entity-framework-core


I'm using Entity Framework Core together with Repository Pattern and I'm having one issue.

I have classes Customer, Company and Email which, hiding things not relevant here, look like the following:

public class Email
    public int EmailId { get; protected set; }

    public string Address { get; protected set; }

    public string Description { get; protected set; }

    public Email(string address, string description)
        if (string.isNullOrEmpty(address))
            throw new ArgumentException(nameof(address));

        if (string.isNullOrEmpty(description))
            throw new ArgumentException(nameof(description));

        this.Address = address;
        this.Description = description;

    protected Email() { }

public class Company
    public int CompanyId { get; protected set; }

    public IList<Email> Emails { get; set; }

public class Customer
    public int CustomerId { get; protected set; }

    public Company Company { get; set; }

The mappings are set so that there is a one-to-one association between Customer and Company while there is a one-to-many association between Company and Email.

On the CustomersRepository I then created the following method:

public IEnumerable<Customer> GetAll()
    return _context.Set<Customer>()
                   .Include(x => x.Company)
                       .ThenInclude(x => x.Emails)
                   as IEnumerable<Customer>;

Now then ThenInclude piece is giving a problem. If I try to use this method, I end up getting one execption saying that source is null.

I've reviewed everything but I didn't find anything wrong. It seems everything is correctly written.

The whole point is: I have entities A, B, C so that A has one of B, and B has many of C, and when I retrieve A I need to get everything associated.

What am I doing wrong here? Why I'm getting this exception?

7/26/2016 6:48:45 PM

Accepted Answer

This seems related to this bug report on Github https://github.com/aspnet/EntityFramework/issues/2274

It was reported as an IOE, then reported fixed, then it came back as a NRE, like your exception. The issue says it's been fixed again, but I'm unsure of in what version and I don't know what version you're currently using.

(Searched for ThenInclude issues in the github repro--there's a TON.)

Sounds unstable. Stay away from it. You can simply avoid the issue altogether by specifying the full path of your include directly

muhCompaniesOrWhatevs.Include(x => x.Company.Emails);
7/27/2016 1:58:10 PM

Related Questions


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