重构EF Core包含语句的长链

I stumbled on a piece of code that looks very repetitive. Unfortunately, I'm not that familiar with LINQ and EF core so I'm curious if this is the correct way to get data. Here is the code. It was actually much longer. I removed some of the repetitive lines for brevity

var result = base.RepositoryContext.Applicant
.Include(c => c.ApplicantEmail)
.Include(c => c.ApplicantStatus)
.Include(c => c.Profile)
.Include(c => c.Profile).ThenInclude(p => p.AssesmentProgram).ThenInclude(cp => cp.Type)
.Include(c => c.Profile).ThenInclude(p => p.AssesmentProgram).ThenInclude(cp => cp.Status)
.Include(c => c.Profile).ThenInclude(p => p.AssesmentProgram).ThenInclude(cp => cp.AssesmentProgramVerification).ThenInclude(cpv => cpv.Verification)
.Include(c => c.Profile).ThenInclude(p => p.AssesmentProgram).ThenInclude(cp => cp.CertRecommendation).ThenInclude(cr => cr.Recommendation)
.Include(c => c.Profile).ThenInclude(p => p.AssesmentProgram).ThenInclude(cp => cp.StatementAssessment).ThenInclude(oa => oa.Coach)
.Include(c => c.Profile).ThenInclude(p => p.AssesmentProgram).ThenInclude(c => c.StatementAssessment).ThenInclude(a => a.Statement)
.Include(c => c.Profile).ThenInclude(p => p.AssesmentProgram).ThenInclude(c => c.StatementAssessment).ThenInclude(o => o.Method)
.Include(c => c.Profile).ThenInclude(p => p.AssesmentProgram).ThenInclude(c => c.StatementAssessment).ThenInclude(a => a.Status)
.Where(...).ToListAsync();

So for example, after it says

.Include(c => c.Profile).ThenInclude(p => p.AssesmentProgram).ThenInclude(c => c.StatementAssessment).ThenInclude(o => o.Method)

it repeats

.Include(c => c.Profile).ThenInclude(p => p.AssesmentProgram).ThenInclude(c => c.StatementAssessment).ThenInclude(a => a.Status)

Do we really have to go through a long chain of .ThenInclude(s) to get to include another table?


Looks like design is not optimal. The include represent a navigational property. It implies foreign key relationships. Let me guess this was code first? Includes are similar to joins.

JohnPeters Yes, it is code first. Is this a symptom of code-first db generation?

Thank you for pointing out this option, however, I would like to avoid hardcoding table relationships as strings. If relationship changes, will the compiler catch this and tell me to update the string?

This is not ideal. No, compiler won't tell you.