Foreach in razor with Many to Many relationship model in the Entity Framework Core

0

I have a table of funcionário and a table of projeto related many to many as shown in the diagram below:

OnthecontrollerFuncionariosControllerintheDetalhesmethodIwanttolistthelistofprojectsthatareinvolved.Inthemethodpopuloamodelandsendtotheviewasbelow:

publicIActionResultDetails(intid){varmodel=newFuncionario();using(varDBContext=newDadosProjetosContext()){model=DBContext.Funcionario.Include(a=>a.FuncionarioProjeto).Where(a=>a.FuncionarioId==id).Single();}returnView(model);}

IntheviewI'mdoingthefollowingforeachtolisttheprojects:

<divclass="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 error System.NullReferenceException: Object reference not set to an instance of an object. when calling the page. How do I fix this?

    
asked by anonymous 04.10.2016 / 04:44

1 answer

0

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

In this case the variable @FP.Projeto is empty, because in the controller, at the moment of making the query using linq, it is not bringing the related projects, only the collection of FuncionarioProjeto because .Include(a => a.FuncionarioProjeto) only includes FuncionarioProjeto and not FuncionarioProjeto.Projeto .

To include FuncionarioProjeto.Projeto in addition to FuncionarioProjeto the .ThenInclude() method is used, 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: link

    
04.10.2016 / 04:44