Using Code First - MVC 4 - EF6 I have the following Model:
[Table("usuario")]
public class Usuario
{
[Key]
[Column("UsuarioId")]
public int UsuarioId { get; set; }
public string Nome { get; set; }
}
[Table("Orcamento")]
public class Orcamento
{
public int OrcamentoId { get; set; }
[ForeignKey("Usuario")]
public int UsuarioId { get; set; }
public virtual Usuario Usuario { get; set; }
}
On my controller, I get a Paged Budget list.
[Authorize]
public ActionResult Index(int? page)
{
OrcamentoService orcamentos = new OrcamentoService();
IQueryable<Orcamento> o = orcamentos.ListarTodos().OrderBy(x => x.OrcamentoId);
int paginaTamanho = 20;
int paginaNumero = (page ?? 1);
IPagedList<Orcamento> orcamento = o.ToPagedList(paginaNumero, paginaTamanho);
return View(orcamento);
}
And in my View, I display in a foreach
@using PagedList;
@using PagedList.Mvc;
@model PagedList.IPagedList<Squadra.Price.Models.Orcamento>
...
@foreach (var item in Model)
{
<tr>
<td>@item.OrcamentoId</td>
<td>@item.Usuario.Nome</td>
</tr>
}
If the User ID is registered, it displays without any problem but if the user ID does not exist, I get the error "Object reference not set to an instance of an object." and the problem is in the navigation '@ item.User.Name'.
Is there a way to display this field if it does not find any ID with this user?