C# Error Nullreferenceexception in Tolist() method

Asked

Viewed 855 times

1

I am working on a C# MVC WEB project with Entityframework. I was able to configure it together with the database and also installed Ninject.

The first controller I’m working on is Users. I want to create an environment for maintaining this data, such as query, add, remove and etc. So I created the classes, controllers, views and etc. For now the database is empty.

I just happen to have a problem with the listing. When trying to call the "Index" View of the "Usuariocontroller", it generates the error below in the "List()" listing method in "User"

An Exception of type 'System.Nullreferenceexception' occurred in Applications.dll but was not handled in user code

Additional information: Object reference not defined for a instance of an object.

Here’s 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 method ToList() does not accept null value and that the solution should instate it before. I made the code below and it did not work with me:

IList<Usuarios> lista = new List<Usuarios>;
lista = this.contexto.usuarios.ToList(); //o erro é aqui
return lista;
  • You have a NullReferenceException on that line because either the field contexto is null, or the field usuarios country contexto is null. Check as the object UsuariosDAO is being created, and as the parameter AplicacoesContexto which is passed to him is created, and see if any of them is null.

1 answer

0


The problem is that the variable uDao 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 of this code - when calling the constructor of UsuarioController. There problem is that the variable contexto is not being initialized. See this 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
}

In fact, the method UsuariosDAO(AplicacoesContexto contexto) (which I imagine is the builder of this class) should not have void in the signature, this should generate a build error.

Another important point

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

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

That’s not quite right. Take a look: o método ToList() não aceita valor nulo, what happens is that you can not call the ToList() (and none another method) in 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 doesn’t make sense either. The ToList() is being applied in contexto.usuarios and not on the variable lista.


The past information is enough to solve your problem, but let me know if you find something missing that I edit the answer with more details.

  • Thanks jbueno! You helped me a lot! I managed to solve the error. Really removing the void from the method that started the variable context in Usuariosdao was the solution! And thanks for the tips too!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.