Object reference not set to an instance of an object - MVC

0

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

  

NullReferenceException: Object reference not set to an instance of an object.

Here's how it is in my model:

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

Loading 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 assembled the same way, and loads the data from the normal referenced table, however in this I can not.

    
asked by anonymous 15.08.2018 / 22:10

1 answer

2

You are not giving include: change the entity's load line to:

var produtoempresa = await db
        .ProdutosEmpresas
            .Include(p => p.ProdutosEmpresas)
        .Where(p => p.ProdutoID == id)
        .ToListAsync();
    
15.08.2018 / 22:24