1
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; }
}
In 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 show 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>
}
In case the User Id exists registered, it displays without any problem but if there is no user ID, I get the error "Object Reference not set to an instance of an Object." and the problem is in the navigation '@item.Usuario.Name'.
There is a way to display this field blank if it does not find any ID with this user?
UsuarioId
on its basis isnot null
? If yes, it should never bring User blank since it is not possible to register budget without user.– ridermansb