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 fieldcontexto
is null, or the fieldusuarios
countrycontexto
is null. Check as the objectUsuariosDAO
is being created, and as the parameterAplicacoesContexto
which is passed to him is created, and see if any of them is null.– carlosfigueira