Perform a Get that takes a List<long> ids as parameters

Asked

Viewed 123 times

0

all right?

I am doing a project in C# and at the moment I am doing the methods to be consumed via API Rest, my boss asked to do an Httpget that receives as parameter a List ids.

I know that in my Controller the method has this structure

[HttpGet("{ids}")]
public async Task<IActionResult> BuscaPorListaIds(IList<long> ids)
        {
            return Response(_mapper.Map<IList<MinhaViewModel>>(_repository.GetListIds));
        }

My doubt is how I can do the method in my Repository, I do not know how I can implement the method to do this query in the database, with several ids, I know that in sql is that way select * from MinhaTabela where id in (1,2,4,5)

So far my Restpository is like this:

public ICollection<MinhaModel> GetListIds(IList<long> ids)
        {
            // Exemplo incompleto, pois não sei como posso fazer esse return para a pesquisa no banco, sei que no final preciso adicionar o .ToList()
            return Db.MinhaModel.AsNoTracking()
        }

Could someone help me? If there’s something wrong with my code, you can tell me OK, pfvr;

  • 1

    This Db.Minhamodel is a list or an object only?

  • I know that at the end I have to put . Tolist() to turn the object into a list

  • 1

    But this Db.Minhamodel, when you stop the mouse on top of it, what kind of value? Is it a collection? List, Array, Ienumerable, Icollection, Iqueryable, Ilist? Something like that?

  • It’s a model, it’s just an object, it’s not a collection

  • 1

    Don’t you know how to pass and receive the parameters in the query string? Or don’t know how to filter in the database query.

  • I don’t know how to filter the query for the bank

Show 1 more comment

1 answer

1


In your Repository do the following Return:

public ICollection<MinhaModel> GetListIds(IList<long> ids)
        {
            return Db.MinhaModel.AsNoTracking().Where(p => ids.Any(x => x == p.Id)).ToList();
        }

You will have to make an adjustment in your Controller, because you are not passing the parameter in your Repospository method and also if you leave it this way, at the time you give the GET, it will give an error, because that way c# understands that you are passing a body in your method, GET should not pass any body type. Then it will be right:

[HttpGet]
public async Task<IActionResult> BuscarPorListaIds([FromQuery] IList<long> id)
{
     return Response(_mapper.Map<IList<MinhaViewModel>>(_repository.GetListIds(id)));
}

Browser other questions tagged

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