C # NullReferenceException error in ToList () method

1

I'm working on a project in C # MVC for WEB with EntityFramework. I was able to set it up next to the database and I also installed Ninject.

The first controller I am working on is Users. I want to create an environment for maintaining such data, such as querying, adding, removing, and so on. So I created the classes, controllers, views, and so on. For now the database is empty.

It happens that I have a problem right in the listing. When trying to call the View "Index" from the "UserController", it generates the below error in the "List ()" listing method in "UsersDAO"

  

An exception of type 'System.NullReferenceException' occurred in   Application.dll but was not handled in user code

     

Additional information: Object reference not set to one   instance of an object.

Here is the code:

UsuarioController

private UsuarioDAO uDao;

public UsuarioController(UsuarioDAO uDao)
{
    this.uDao = uDao;
}
public ActionResult Index()
{
    IList<Usuarios> usuarios = uDao.Lista();
    return View(usuarios);
}

UsuariosDAO

private AplicacoesContexto contexto;
public void UsuariosDAO(AplicacoesContexto contexto)
{
 this.contexto = contexto;
}

public IList<Usuarios> Lista()
{    
    return contexto.usuarios.ToList(); //o erro é aqui    
}

Index.cshtml de UsuarioController

@model IList<Aplicacoes.Entidades.Usuarios>

@{
    ViewBag.Title = "Usuários";
}
<h4>Lista de Usuários</h4>
<table class="table">
    <thead>
        <tr>
            <th>Id</th>
            <th>Matricula</th>
            <th>DV</th>
            <th>Nome</th>
            <th>Cargo</th>
            <th>Função</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var usuario in @Model)
        {
            <tr>
                <td>@usuario.Id</td>
                <td>@usuario.Matricula</td>
                <td>@usuario.MatriculaDV</td>
                <td>@usuario.Nome</td>
                <td>@usuario.Cargo.Cargo</td>
                <td>@usuario.Funcao.Funcao</td>
            </tr>
        }
    </tbody>
</table>

Usuarios.cs - Model

public class Usuarios
{    
    public int Id { get; set; }

    [Required, StringLength(60)]
    public string Nome { get; set; }

    //Outras propriedades
}

What I found on the internet describes me that the ToList() method does not accept null value and that the solution should instantiate it before. I made the code below and it did not work for me:

IList<Usuarios> lista = new List<Usuarios>;
lista = this.contexto.usuarios.ToList(); //o erro é aqui
return lista;
    
asked by anonymous 17.02.2016 / 02:11

1 answer

0

The problem is that the uDao variable is not being initialized at any time, at least not in the code that was posted in the question. See this excerpt

private UsuarioDAO uDao;

public UsuarioController(UsuarioDAO uDao)
{
    this.uDao = uDao;
}
public ActionResult Index()
{
    IList<Usuarios> usuarios = uDao.Lista(); //NullReferenceException - uDao é nulo
}

If this variable is being initialized outside this code - when calling the constructor of UsuarioController . The problem is that the contexto variable is not being initialized. Here's a snippet of code:

private AplicacoesContexto contexto;
public void UsuariosDAO(AplicacoesContexto contexto)
{
   this.contexto = contexto;
}

public IList<Usuarios> Lista()
{
    return contexto.usuarios.ToList(); 
    //contexto pode estar nulo, certifique-se de ter inicializado a variável
}

Incidentally, the UsuariosDAO(AplicacoesContexto contexto) method (which I imagine is the constructor of this class) should not have void in the signature, this should generate a compilation error.

Another important point

  

What I found on the internet describes me that the ToList() method does not accept null value and that the solution should instantiate it before. I made the code below and it did not work for me:

IList<Usuarios> lista = new List<Usuarios>;
lista = this.contexto.usuarios.ToList();

That's not quite right. You see, o método ToList() não aceita valor nulo , what happens is that you can not call ToList() (and no other method) on variables that are null. See the example:

string[] array = null;
List<string> list = array.ToList(); //NullReferenceException -> array é null    
var query = array.Where(x => x == "umaString"); //NullReferenceException  -> array é null

The code also makes no sense. The ToList() is being applied in contexto.usuarios and not in the lista variable.

    

17.02.2016 / 11:20