Base solution for your next web application
Open Closed

Get nested relationships in repository #4338


User avatar
0
klawsuc created

Not sure if the subject line reflects what I want. I have a repository for a Company which has a relationship to CompanyAddresses which in turn has a relationship to Addresses. I have the following code to get the Company and related data. However I would like to get the actual Addresses referenced in the CompanyAddresses table in the same query if possible.

var company = await _companyRepository
                    .GetAllIncluding(
                        c => c.Patients,
                        c => c.CompanyAddresses,
                        c => c.CompanyEmails,
                        c => c.CompanyPhones
                    )
                    .FirstOrDefaultAsync(o => o.Id == input.Id);

Company class has the following:

public virtual ICollection<Patient> Patients { get; set; }
public virtual ICollection<CompanyAddress> CompanyAddresses { get; set; }
public virtual ICollection<CompanyEmail> CompanyEmails { get; set; }
public virtual ICollection<CompanyPhone> CompanyPhones { get; set; }

1 Answer(s)
  • User Avatar
    0
    aaron created
    Support Team

    To include nested relationships, add using Microsoft.EntityFrameworkCore; and do:

    var company = await _companyRepository
                        .GetAllIncluding(
                            c => c.Patients,
                            c => c.CompanyEmails,
                            c => c.CompanyPhones
                        )
                        .Include(c => c.CompanyAddresses)
                            .ThenInclude(ca => ca.Address)
                        .FirstOrDefaultAsync(o => o.Id == input.Id);