LINQ query null reference exception

廉价感情. 提交于 2019-12-13 04:45:44

问题


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!


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/2403903/linq-query-null-reference-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!