Getting Foreign Key value - Object Reference not set to an instance of an Object

Asked

Viewed 211 times

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 is not null? If yes, it should never bring User blank since it is not possible to register budget without user.

2 answers

2

Your model is missing the relationship (1 user may have 1 or multiple budgets) and in the code to ensure use Include since your relationship by question is mandatory, and the method Include requires loading the relationship.

Changes

//////////////////////////////////////////////////////////////////////
[Table("usuario")]
public class Usuario
{
    public Pessoas()
    {
        this.Orcamentos = new HashSet<Orcamentos>();
    }       
    [Key]
    [Column("UsuarioId")]
    public int UsuarioId { get; set; }
    public string Nome { get; set; }    
    public virtual ICollection<Orcamento> Orcamentos { 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; }
}
//////////////////////////////////////////////////////////////////////
[Authorize]
public ActionResult Index(int? page)
{
    OrcamentoService orcamentos = new OrcamentoService();
    IQueryable<Orcamento> o = orcamentos.ListarTodos()
                                        .Include(inc => inc.Usuario)
                                        .OrderBy(x => x.OrcamentoId);
    int paginaTamanho = 20;
    int paginaNumero = (page ?? 1);
    IPagedList<Orcamento> orcamento = o.ToPagedList(paginaNumero, paginaTamanho);
    return View(orcamento);
}
//////////////////////////////////////////////////////////////////////
  • It worked! Include requires to have the relation, so the table row is only displayed if there is a relation, so I did not use it and added the condition that @Ciganomorrisonmendez indicated and solved 100% my problem! Thanks again!

1

Change:

<td>@item.Usuario.Nome</td>

For:

<td>@(item.Usuario != null ? item.Usuario.Nome : "")</td>
  • An explanation of why doing so would make the answer much better, in my view.

  • 1

    @Jorgeb simple because this user object will be null if no user is associated with the budget. So when displaying a property of this object, it is necessary to validate if it is filled.

  • @Jorgeb. Explain the obvious?

  • @Gypsy omorrisonmendez not everyone knows the obvious, it was just a suggestion.

  • I set up my Model relationship, as @Harrypotter helped and used this condition on my chart and it worked perfectly! Thanks!

Browser other questions tagged

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