Problem with Linq in Lambda: LINQ to Entities does not recognize ... get_Item (Int32). How to solve?

3

When trying to execute the loop for (when the query is executed) it is giving error in my lambda expression:

var funcionarios = repository.Funcionarios
    .Include(x => x.Cargo)
    .Include(x => x.Bairro)
    .Include(x => x.Bairro.Cidade)
    .Include(x => x.Historicos)
    .Where(x => x.Historicos
        .Count(hist => hist.TipoHistoricoId == parametros.HistoricoManutencaoCargoId &&
            hist.DataRegistro.Year == AnoBase) > 0)
    .Where(x => x.Bairro != null && x.Bairro.Cidade != null)
    .OrderBy(x => x.Bairro.Cidade.Id)
    .ThenByDescending(x => x.Historicos[0].DataRegistro);

foreach (var func in funcionarios)
{
...
}

I'm getting the following error:

  

LINQ to Entities does not recognize the method 'Domain.FuntionaryHistorical get_Item (Int32)' method, and this method can not be translated into a store expression.

Domain.FuncionarioHistorico refers to the Historicos property of the Employee being loaded by: .Include(x => x.Historicos) .

>

parametros is a local variable that stores some system parameters, including the History Type that is used for maintaining charges. HistoricoManutencaoCargoId is the property that accesses Id of that type.

If I need the template I add a small example because the current one is large.

How do I resolve this?

    
asked by anonymous 18.08.2014 / 23:48

1 answer

2

Include expects a related complex object from your Model : link

Therefore, what causes the problem is not Include , but Count , which within Where can not be translated immediately. So the error.

In any case, this way that is written is strange. You can simplify it to:

var funcionarios = repository.Funcionarios
    .Include(x => x.Cargo)
    .Include(x => x.Bairro)
    .Include(x => x.Bairro.Cidade)
    .Include(x => x.Historicos)
    .Where(x => x.Bairro != null && x.Bairro.Cidade != null)
    .OrderBy(x => x.Bairro.Cidade.Id)
    .ThenByDescending(x => x.Historicos[0].DataRegistro);

funcionarios = funcionarios.SelectMany(f => f.Historicos)
    .Where(hist => hist.TipoHistoricoId == parametros.HistoricoManutencaoCargoId &&
            hist.DataRegistro.Year == AnoBase)
    .Select(hist => hist.Funcionario)
    .ToList();
    
19.08.2014 / 00:09