【问题标题】:Entity Framework ThenInclude doesn't include properties of the grandchild实体框架 ThenInclude 不包括孙子的属性
【发布时间】:2020-06-16 14:27:33
【问题描述】:

实体框架 ThenInclude 不包括孙子的任何属性。当我尝试访问“GrandChild”的属性“Total”时,我收到错误消息“CS1061 'ICollection' 不包含'Total' 的定义并且没有可访问的扩展方法'Total'”。 intellosense 根本不适用于“GrandChild”。它适用于“Child”,但不适用于“GrandChild”。当我从 Postman 发出请求时,我可以看到 Entity 包含“GrandChild”并且它肯定具有“Total”属性(以及所有其他属性)。

var products = dbf.Products
                .Include(a=>a.Child)
                .ThenInclude(b => b.GrandChild)          
                .Where(c => c.ProId >72200);

            foreach(var p in products)
            {
               p.Child.GrandChild.Total// I get error here

            }

【问题讨论】:

  • ICollection 没有属性 Total 它有属性 Count
  • GrandChild 是该属性的一个坏名称,它应该类似于 GrandChildren,这应该让您更好地了解出了什么问题。相反,您需要遍历该集合,或执行Child.GrandChild.First().Total 之类的操作
  • 感谢您提供宝贵的信息。但问题是我如何才能使用 ThenInclude 访问该属性(如果 ThenInclude 不允许访问属性,它的目的是什么?
  • 你不能。 ThenInclude 不负责访问该属性。它确保加载了 GrandChild(再次,非常糟糕的 oclection 命名),您需要在代码中迭代子项。

标签: .net entity-framework-core


【解决方案1】:

试试这个访问 GrandChild 的所有属性:

var totals = p.Child.GrandChild.Select(gc=> gc.Total);

但如果你想得到总孙子(孙子的数量),你应该试试这个:

var count = p.Child.GrandChild.Count();

【讨论】:

    【解决方案2】:

    错误很明显,还是?

    GrandChild 是一个 ICollection(如果您提供相关的类定义,我们可以看到它)。 ICollection 上没有 Total 函数。时期。从来不是。这根本不是一个实体框架问题——你基本上假设 ThenInclude 会神奇地为 ICollection 提供一个属性 Total。

    这应该如何工作,因为 Total 需要知道如何添加,除非集合中的元素是任何类型的标量,这是根本不可能的。

    使用逻辑计算总数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-05
      • 2020-02-12
      • 2017-03-02
      • 2012-06-05
      • 1970-01-01
      • 2013-09-06
      • 2018-07-04
      • 1970-01-01
      相关资源
      最近更新 更多