NullReferenceException error in join

0

I created a join in LINQ to create a List :

(from p in listaProcedimento
    join pd in oListaprocedimentodetalhe on p.codigo equals pd.codigoProcedimento into pd1
    from pd2 in pd1.DefaultIfEmpty()
    select new ProcedimentoDetalhe()
    {
        codigoDetalhe = pd2.codigoDetalhe == null ? "000" : "012",
        codigoProcedimento = p.codigo,
        descricao = p.descricao,
        idadeMax = p.idadeMax,
        idadeMin = p.idadeMin
    }).OrderBy(p => p.descricao)
      .ToList();

I get the error saying that pd2 was null , being that I already tried to correct this in line: pd2.codigoDetalhe == null ? "000" : "012" .

Why is not it working?

    
asked by anonymous 02.08.2017 / 13:42

3 answers

3

I am finding this code strange, but it is not doing what it imagines. You are not analyzing whether p2 is null is analyzing if a field of it ( pd2.codigoDetalhe ) is null, which is too late because the p2 itself is null and it already gives error and can not analyze its field does not exist since it would be a field of something null. The correct would be:

codigoDetalhe = pd2 == null ? "000" : "012",

I still do not know if this is the final solution, but it solves the question that is in the question.

Can you guarantee that the field is never null? If you can not have to check it too, like this:

codigoDetalhe = pd2 == null || pd2.codigoDetalhe == null ? "000" : "012",
    
02.08.2017 / 13:48
2

Because what is null is pd2 , not pd2.codigoDetalhe property.

Try this:

codigoDetalhe = pd2 == null ? "000" : "012",
    
02.08.2017 / 13:47
1

Change your line to compare pd2 and codeDetails if they are equal to null

codigoDetalhe = pd2 == null && pd2.codigoDetalhe == null ? "000" : "012",

A curious thing is that you change the value of CodeDetail to another value.

If you're dealing with lists, you'd do something more performative like this.

(from p in listaProcedimento
    select new ProcedimentoDetalhe()
    {
        codigoDetalhe = (oListaprocedimentodetalhe.any(pd => p.codigo == pd.codigoProcedimento && pd.codigoDetalhe != null) ? "012" : "000" ,
        codigoProcedimento = p.codigo,
        descricao = p.descricao,
        idadeMax = p.idadeMax,
        idadeMin = p.idadeMin
    }).OrderBy(p => p.descricao)
      .ToList();

Within your select would check your field.

(oListaprocedimentodetalhe.any(pd => p.codigo == pd.codigoProcedimento && pd.codigoDetalhe ! null)
    
02.08.2017 / 14:00