Object Reference not set to an instance of an Object - MVC

Asked

Viewed 140 times

0

I am loading a table, and doing the debugging, it brings the data perfectly, but when I get the data of the table reference in the foreign key, it is returning me the following error:

Nullreferenceexception: Object Reference not set to an instance of an Object.

Here’s how it’s in my model:

  public int Id { get; set; }
    public Empresa EmpresaProduto { get; set; }
    public int EmpresaID { get; set; }

Clicking on the controller:

  var produtoempresa = await db.ProdutosEmpresas.Where(p => p.ProdutoID == id).ToListAsync();

And here is my table:

<table class="table table-responsive table-hover">
                        <tbody>
                            @foreach (var item in Model.ProdutosEmpresas)
                            {
                                <tr>
                                    <td>@item.EmpresaProduto.RazaoSocial</td>
                                    <td>@item.QtdAtual</td>
                                </tr>
                            }
                        </tbody>
                    </table>

I have another table, which was mounted in the same way, and load the data from the normal referenced table, but in this I can not.

1 answer

2


You are not giving include: change the entities' loading line to:

var produtoempresa = await db
        .ProdutosEmpresas
            .Include(p => p.ProdutosEmpresas)
        .Where(p => p.ProdutoID == id)
        .ToListAsync();
  • So it works, but the strange thing is that I do the same thing in another table, and does not return me this error, should be something in the bank, rs Thanks.

  • There may be several reasons Mariana, if the property is virtual, will load by Lazy Loading, if it is not marked with virtual will load only with Eager Loading (use of Include). I advise you to read the RU documentation.

Browser other questions tagged

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