Foreach on Razor with Many to Many Relationship Model in Entity Framework Core

Asked

Viewed 134 times

0

I have a table of funcionário and a table of projeto related to many to many as shows diagram below: Diagrama demostrando as tabelas

At the controller FuncionariosController in the method Detalhes i want to list the list of projects they are involved in. In the method populate the model and send to the view as below:

    public IActionResult Details(int id)
    {
        var model = new Funcionario();
        using( var DBContext = new DadosProjetosContext() ) {
            model = DBContext.Funcionario
            .Include(a => a.FuncionarioProjeto)
            .Where(a => a.FuncionarioId == id )
            .Single()
            ;}

        return View(model);
    }

In the view I’m doing the following foreach to list the projects:

    <div class="container">
        @foreach (var FP in Model.FuncionarioProjeto) {
            <a asp-controller="Projetos" asp-action="Detalhes" asp-route-id="@FP.Projeto.ProjetoId" class="btn-bracketed">
                @FP.Projeto.Nome
            </a>
            <br>
        }
    </div>

But I’m getting the bug System.NullReferenceException: Object reference not set to an instance of an object. when calling the page. How to solve this problem?

1 answer

0


The exception System.NullReferenceException: Object reference not set to an instance of an object. usually due to the attempt to access an empty object using Razor.

In this case the variable @FP.Projeto is empty, that’s because in the controller, at the time of query using Linux is not bringing the related projects, only the collection of FuncionarioProjeto due to the .Include(a => a.FuncionarioProjeto) only include FuncionarioProjeto and not FuncionarioProjeto.Projeto.

To include the FuncionarioProjeto.Projeto besides FuncionarioProjeto the method is used .ThenInclude(), resulting in the following:

    public IActionResult Details(int id)
    {
        var model = new Funcionario();
        using( var DBContext = new DadosProjetosContext() ) {
            model = DBContext.Funcionario
            .Include(a => a.FuncionarioProjeto)
            .ThenInclude(b => b.Projeto)
            .Where(a => a.FuncionarioId == id )
            .Single()
            ;}

        return View(model);
    }

Source: https://docs.efproject.net/en/latest/querying/related-data.html

Browser other questions tagged

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