user289082
user289082

Reputation: 25

LINQ query null reference exception

I have the next query:

  var bPermisos = from b in ruc.Permisos
                      where b.IdUsuario == cu.Id
                          select new Permisos(){
                              Id=b.Id,
                              IdUsuario=b.Id,
                              IdPerfil=b.Id,
                              Estatus=b.Estatus
                          };
  var qSisPer = from perm in bPermisos
                      **select new {                    
                          perm.IdPerfil,
                          perm.Cat_Perfil.Nivel,
                          perm.Cat_Perfil.Nombre,   
                          Nombre_Sistem=perm.Cat_Perfil.Cat_Sistema.Nombre**
                      };

And is throwing me an exception, plz help!

Upvotes: 0

Views: 1098

Answers (2)

Jay
Jay

Reputation: 57939

For starters, I think the first query can probably be rewritten as:

var bPermisos = ruc.Permisos.Where(b => b.IdUsuario == cu.Id);

Beyond that, it is rather unclear what your code is doing. You appear to be re-projecting the results you already have -- taking items of a known type and creating an anonymous type to hold them. Furthermore, the second projection is accessing a bunch of members that were not selected in the first query.

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564441

This could be happening because of any of the following:

  • cu is null
  • One element in ruc.Permisos is null, causing the exception on b.IdUsuario

If it's the latter, you can just handle this by adding:

var bPermisos = from b in ruc.Permisos
                where b != null && b.IdUsuario == cu.Id
                 // ... rest of your code

Upvotes: 0

Related Questions