【问题标题】:Refactor EF Core long chain of Include statement重构包含语句的 EF Core 长链
【发布时间】:2020-03-26 03:33:29
【问题描述】:

我偶然发现了一段看起来非常重复的代码。不幸的是,我对 LINQ 和 EF 核心不太熟悉,所以我很好奇这是否是获取数据的正确方法。这是代码。它实际上要长得多。为简洁起见,我删除了一些重复的行

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();

例如,在它说之后

.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)

我们真的必须经过一长串 .ThenInclude(s) 才能包含另一个表吗?

【问题讨论】:

  • 看起来设计不是最优的。包含表示导航属性。它暗示外键关系。让我猜这是代码第一?包含类似于联接。
  • @JohnPeters 是的,这是代码优先。这是代码优先数据库生成的症状吗?

标签: entity-framework entity-framework-core


【解决方案1】:

长度更短一点的方法是使用字符串而不是 lambda 表达式。

base.RepositoryContext.Applicant.Include("Profile.AssesmentProgram.StatementAssessment.Method")

【讨论】:

  • 感谢您指出此选项,但是,我想避免将表关系硬编码为字符串。如果关系发生变化,编译器会捕捉到这一点并告诉我更新字符串吗?
  • 这并不理想。不,编译器不会告诉你。
猜你喜欢
  • 2020-05-11
  • 2020-08-14
  • 2013-05-23
  • 2020-03-19
  • 1970-01-01
  • 2021-07-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多