Refactor EF Core long chain of Include statement

entity-framework entity-framework-core

Question

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?

1
1
3/26/2020 3:33:29 AM

Popular Answer

A little bit shorter length way is using string instead of lambda expression.

base.RepositoryContext.Applicant.Include("Profile.AssesmentProgram.StatementAssessment.Method")
0
3/26/2020 3:52:55 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