2016-10-11 163 views
1

我想包括子屬性的屬性,而是返回空,即使我用包容的財產包括嵌套嵌套子與LINQ

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

+3

EF被稱爲忽略包括正在使用投影(選擇)像你的。 –

+0

@IvanStoev你知道我該如何解決這個問題? –

回答

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, 
    });