【问题标题】:Entity Framework Include() : A specified Include path is not valid实体框架包含():指定的包含路径无效
【发布时间】:2015-10-05 21:31:40
【问题描述】:

我的以下实体框架语句一直在正常工作。

CostingEvent targetEvent = repository.Query<CostingEvent>()
                                     .FirstOrDefault(ce => ce.Id == targetId);

但是,我需要禁用此代码的延迟加载,因此我在前面的语句中添加了 Include() 元素:

CostingEvent targetEvent = repository.Query<CostingEvent>()
                                     .Include(ce => ce.ProposalSection.Proposal.Costing)
                                     .FirstOrDefault(ce => ce.Id == targetId);

但是,这会产生运行时异常:

指定的包含路径无效。 EntityType 'Leo.Domain.CostingEvent' 没有声明名为 'Costing' 的导航属性。

我真的不明白这个错误。首先,我没有引用CostingEvent.Costing,我引用的是CostingEvent.ProposalSection.Proposal.Costing。此外,这些都是显示在 Intellisense 中的有效导航属性。

注意:这是一个数据库优先的应用程序。另请注意:repository 是一个包装类,但 Include() 引用是标准实体框架。

【问题讨论】:

  • 我假设所有属性都已映射?
  • 您能否提供相应课程的要点?这应该可以正常工作。

标签: c# .net entity-framework


【解决方案1】:

嵌套的 EF 包含很棘手。

你考虑过

CostingEvent targetEvent = repository.Query<CostingEvent>()
                                .Include("ProposalSection.Proposal.Costing")
                                .FirstOrDefault(ce => ce.Id == targetId);

这也可能有效

CostingEvent targetEvent = repository.Query<CostingEvent>()
                                .Include(ce => ce.ProposalSection)
                                .Include(ce => ce.ProposalSection.Proposal)
                                .Include(ce => ce.ProposalSection.Proposal.Costing)
                                .FirstOrDefault(ce => ce.Id == targetId);

【讨论】:

  • 我看到支持语法,但我不明白为什么会有所不同。
  • 没有什么不同,第三个 Include 就是你所需要的(它暗示了前两个)。
【解决方案2】:

您需要像这样选择子导航属性:

CostingEvent targetEvent = repository.Query<CostingEvent>()
                                     .Include(ce => ce.ProposalSection.Select(ps=>ps.Proposal.Select(p=>p.Costing)))
                                     .FirstOrDefault(ce => ce.Id == targetId);

【讨论】:

  • Select() 不需要点左侧的集合吗? ProposalSectionProposal 都是单数。
  • 是的,选择通常确实需要左侧的集合。 Costing 是导航属性还是仅仅是 Proposal 的属性?如果 Costing 只是一个常规属性,那么你不需要它,只需以 Proposal 结束即可。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-05
  • 1970-01-01
相关资源
最近更新 更多