Consume web api with several models

1

In this my question Doubt GET WebApi I face some error due to relationships . But now taking it as a basis on account of my models, how could I consume this service? Because the Table1 model has relationships and I needed to bring them to the MVC I'm using to consume ... But what happens is that relationships, models, are not filled, come null ...

My controller in ASP.NET MVC:

    public ActionResult Index()
    {
        //Varialvel resposável por receber os dados que estão no banco de dados para mostrar na tela
        HttpResponseMessage resposta = cliente.GetAsync("http://meuservico/api/servico").Result;

        //Se der tudo certo, é porque trouxe os dados retornando código 200
        if (resposta.IsSuccessStatusCode)
        {
            //Formata o json para mostrar na tela
            var result = resposta.Content.ReadAsAsync<IEnumerable<Tabela1>>().Result;

            //retorna para a tela os json formatado
            return View(result);
        }

        //Caso tenha dado errado, retorna somente a tela sem dado algum
        return View();
    }

The variable result brings the model Table1 prequel, but your relationships do not ... What could be happening?

    
asked by anonymous 30.03.2017 / 03:41

1 answer

0

According to the link response code:

public IQueryable GetVerb()
{
    var dados = from d in db.Tabela1
                join a in db.Tabela2 on d.Tabela1_Tabela2Id equals a.Tabela2Id
                select new 
                {
                    nome = d.Nome,
                    cnpj = d.CNPJ,
                    endereco = a.Endereco,
                    cidade = a.Cidade,
                    cep = a.CEP,
                };

    return (dados);             
}

The GetVerb() method returns a list of a generic that was created in select . So if you're restricting returning all Tabela1 tails along with your Tabela2 relationships, there's no way for your API consumers to get this data.

public IQueryable GetVerb()
{
    var dados = from d in db.Tabela1
                join a in db.Tabela2 on d.Tabela1_Tabela2Id equals a.Tabela2Id
                select new 
                {
                    nome = d.Nome,
                    cnpj = d.CNPJ,
                    endereco = a.Endereco,
                    cidade = a.Cidade,
                    cep = a.CEP,
                    tabela2 = a // <====
                };

    return (dados);             
}

Finally, turn all your asynchronous flow:

public async Task<ActionResult> Index()
{
    var response = await cliente.GetAsync("http://meuservico/api/servico");
    if (!response.IsSuccessStatusCode) return View();

    var list = await response.Content.ReadAsAsync<IEnumerable<Table1>>();
    return View(list);
}
    
30.03.2017 / 10:37