【问题标题】:How to get childs of child of a parent Entity Framework如何获取父实体框架的孩子的孩子
【发布时间】:2019-03-17 08:12:23
【问题描述】:

我有 3 张桌子

Inventarios -> Localizacoes -> Etiquetas

从左到右都有一对多的关系

问题是我似乎无法达到礼仪

// GET: api/Inventarios
public IQueryable<Inventario> GetInventarios()
{
    var inventarios = db.Inventarios.Include(i => i.Localizacoes.Select(l => 
                                                 l.Etiquetas.SelectMany(e => e.Numero)));
    return inventarios;
}

这里是模型

public class Inventario
{
    public int InventarioID { get; set; }
    public string Colaborador { get; set; }
    public string Armazem { get; set; }
    public decimal Total { get; set; }
    public DateTime Data { get; set; }

    public ICollection<Localizacao> Localizacoes { get; set; }
}

public class Localizacao
{
    public int LocalizacaoID { get; set; }
    public string Referencia { get; set; }
    public int EtiquetasPorInventariar { get; set; }
    public int EtiquetasInventariadas { get; set; }
    public bool IsValid { get; set; }
    public decimal Precisao { get; set; }

    public int InventarioID { get; set; }
    public Inventario Inventario { get; set; }

    public ICollection<Etiqueta> Etiquetas{ get; set; }
}

public class Etiqueta
{
    public int EtiquetaID { get; set; }
    public string Numero { get; set; }

    public int LocalizacaoID { get; set; }
    public Localizacao Localizacao { get; set; }
}

这是我从 api 请求进入浏览器控制台的异常

"包含路径表达式必须引用导航属性 在类型上定义。使用虚线路径进行参考导航 属性和用于集合导航的 Select 运算符 属性。”

【问题讨论】:

  • SelectMany 看起来不正确,而且您返回 IQueryable 的事实也很可疑
  • 为什么会这样?我认为它是从 Controller 类生成的,但我不记得了
  • 从您的问题中不清楚您到底想得到什么? 所有行来自Etiqueta?您没有任何 where 子句。

标签: c# entity-framework


【解决方案1】:

我的假设是您使用 IQueryable 来获得 OData 支持

除此之外,我在这里看到的两件事看起来不太正确

第一个,是SelectMany,应该是Select

var inventarios = db.Inventarios.Include(i => i.Localizacoes.Select(l => 
                                             l.Etiquetas.Select(e => e.Numero)));

第二个,是你返回IQueryable,我不确定这是否会遍历对象图。

作为测试,你可以做这样的事情

return inventarios.ToList().AsQuerable(); 

【讨论】:

  • 是的,它与 select 一起使用,但我仍然是使用 linq 的初学者。但无论哪种方式,它都会以正确的格式返回 json 数据并显示在具有 2 个嵌套表的表中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-29
  • 2013-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多