包含嵌套子嵌套LINQ的嵌套

时间:2016-10-11 13:09:58

标签: c# entity-framework linq

我试图包含子属性的属性,但是返回为null,即使我使用包含属性

 var notas =
                dtx.NFeItem.Where(n => n.Empresa.EmpresaId == empresa.EmpresaId)
                    .Where(n => n.NFe.ide_dEmi.Value.Year >= anoInicial)
                    .Where(n => n.NFe.ide_dEmi.Value.Month >= mesInicial)
                    .Where(n => n.NFe.ide_dEmi.Value.Year <= anoFinal)
                    .Where(n => n.NFe.ide_dEmi.Value.Month <= mesFinal)
                    .Where(n => n.NFe.ide_tpNF == "1")
                    .Include(n => n.NFe)
                    .Include(n => n.NFe.participante.Empresa)
                    .GroupBy(g => new { g.CST_ICMS, g.CFOP, g.aliqICMS, g.pRedBC_ICMS, g.NFe.ide_dEmi.Value.Month, g.NFe.ide_dEmi.Value.Year, g.NFe.participante })
                    .Select(i => new { i.Key.CFOP, CST = i.Key.CST_ICMS, pICMS = i.Key.aliqICMS, pRedBC = i.Key.pRedBC_ICMS, mes = i.Key.Month, ano = i.Key.Year, NFePart = i.Key.participante });

即使使用Include(n => n.NFe.participante.Empresa),该属性也会返回null

然后我做了秋天

 var periodos = notas.DistinctBy(i => new { i.ano, i.mes }).Select(i => new { i.ano, i.mes }).ToList();


            foreach (var periodo in periodos)
            {

                var notasPeriodo = notas.Where(i => i.ano == periodo.ano && i.mes == periodo.mes).ToList();
                var participantes = notasPeriodo.DistinctBy(p => p.NFePart.CNPJ).Select(i => i.NFePart).ToList();


    //etc.....
    }

结果:

enter image description here

1 个答案:

答案 0 :(得分:2)

如果最终查询结果元素类型不是用作包含的根的实体,则

EF忽略Include表达式。

您可以做的是在查询投影中包含所需的属性,并依靠EF导航属性修正将它们绑定到引用它们的相应对象:

var notas = dtx.NFeItem
    .Where(n => n.Empresa.EmpresaId == empresa.EmpresaId)
    .Where(n => n.NFe.ide_dEmi.Value.Year >= anoInicial)
    .Where(n => n.NFe.ide_dEmi.Value.Month >= mesInicial)
    .Where(n => n.NFe.ide_dEmi.Value.Year <= anoFinal)
    .Where(n => n.NFe.ide_dEmi.Value.Month <= mesFinal)
    .Where(n => n.NFe.ide_tpNF == "1")
    .GroupBy(g => new { g.CST_ICMS, g.CFOP, g.aliqICMS, g.pRedBC_ICMS, g.NFe.ide_dEmi.Value.Month, g.NFe.ide_dEmi.Value.Year, g.NFe.participante })
    .Select(i => new
    { 
        i.Key.CFOP,
        CST = i.Key.CST_ICMS,
        pICMS = i.Key.aliqICMS,
        pRedBC = i.Key.pRedBC_ICMS,
        mes = i.Key.Month,
        ano = i.Key.Year,
        NFePart = i.Key.participante,
        // include properties:
        i.Key.participante.Empresa,
    });
相关问题