Get Method with Customizable Where

Asked

Viewed 38 times

1

I made a WebAPI (ASPNET with EF6) with verb support Get(), Post() and Delete(). At some point, I need to access certain values that are not returned by default by verbs, for example:

The Order Controller has a method Get() that will return the entire listing and a method Get(int id) that will bring the request by ID, but if I want a request by the Id of the related establishment I would have to take all the Orders and filter in the application. It would make the requisition too heavy.

I’d like to make a Get() that receives, for example, a parameter where and a parameter with the value I expect from Where, for example id_estabelecimento/3. Is it possible to accomplish such a feat? There is a better way to treat this kind of demand?

  • Language? Framework?

  • Sorry, @Virgilionovic, I added to the question

  • and if you do a method for it! just do another method and put the verb get too!

  • 1

    @Csorgo search in Odata for Entity framework. I’m running out of time to make an example now, but I think you can find good stuff on the internet.

  • could be a little clearer ? you a method of your control or an EF get method ? that receives a query ? post your code as you tried to do even if wrong.

1 answer

3


Thank you very much for your comments from colleagues in the community. I talked to a colleague yesterday about the problem and saw that the best way (for security and usability reasons) is to create endpoints according to what my application will need. I used some of the pattern ViewModel and created a new endpoint to return only what I need. Follow below with comments:

    [HttpGet]
    [Route("order/estabelecimento/{id}")] //Rota definida a partir do estabelecimento/ para não conflitar com outro endpoint
    public async Task<List<ordemViewModel>> GetByEstablishmentId(string id)
    {
        new OrdemController();
        List <ordemViewModel> orders = await (from itens in db.ordem where itens.id_estabelecimento == id select new ordemViewModel
         //Cria um ViewModel do tipo ordem e solicita apenas os dados que preciso
        { 
          id = itens.id,
          preco = itens.preco
          dataCriacao = itens.dataCriacao
          //Dados que eu preciso
        }).ToListAsync();
        if (!orders.Any())
        {
            HttpResponseMessage error = new HttpResponseMessage(HttpStatusCode.NotFound)
            {
                Content = new StringContent(string.Format("Nenhuma ordem encontrada")),
                StatusCode = HttpStatusCode.NotFound,
                ReasonPhrase = "Order Not Found"
            };
            throw new HttpResponseException(error);
        }
        return orders;
    }

Browser other questions tagged

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