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;