# 8.1.2 Creando el query

Los objetos query nos van a permitir consultar la información de nuestros servicios.&#x20;

Para poder realizar el filtrado con graphql se debe regresar un IQueryable por lo cual vamos a agregar una función ObtenerIQueryable en nuestra clase AccesoDAO

{% code title="AccesoDAO.cs" %}

```csharp
/// <summary>
/// Regresa todos los registros como IQueryable
/// </summary>
/// <returns></returns>
public IQueryable<TEntity> ObtenerIQueryable()
{
    return contexto.Set<TEntity>();
}
```

{% endcode %}

### Creando CaducidadDAO

Vamos a crear la clase para obtener los datos de las caducidades, con todas las funciones básicas.

{% code title="CaducidadDAO.cs" %}

```csharp
public class CaducidadDAO
{
    private readonly CaducaContext contexto;
    private readonly LocService localizacion;

    private readonly AccesoDAO<Caducidad> caducidadDAO;

    public CustomError customError;

    public CaducidadDAO(CaducaContext context, LocService locService)
    {
        this.contexto = context;
        this.localizacion = locService;
        caducidadDAO = new AccesoDAO<Caducidad>(context, locService);
    }

    public async Task<List<Caducidad>> ObtenerTodoAsync()
    {
         return await caducidadDAO.ObtenerTodoAsync();
    }

    public List<Caducidad> ObtenerTodo()
    {
        return caducidadDAO.ObtenerTodo();
    }
    
    public async Task<Caducidad> ObtenerPorIdAsync(int id)
    {
         return await caducidadDAO.ObtenerPorIdAsync(id);
    }

    public async Task<bool> AgregarAsync(Caducidad caducidad)
    {
         List<IRegla> reglas = new List<Core.IRegla>();
         if (await caducidadDAO
                 .AgregarAsync(caducidad, reglas))
             return true;
         else
         {
             customError = caducidadDAO.customError;
             return false;
         }
    }
      
    public async Task<bool> ModificarAsync(Cliente cliente)
    {
        List<IRegla> reglas = new List<Core.IRegla>();
        if (await clienteDAO.ModificarAsync(cliente, reglas))
                return true;
        else
        {
                customError = clienteDAO.customError;
                return false;
        
        }
    }

    public async Task<bool> BorraAsync(int id)
    {
        var caducidad = await ObtenerPorIdAsync(id);
        if (caducidad == null)
        {
            customError = new CustomError(404, String.
                Format(this.localizacion
                  .GetLocalizedHtmlString("NotFound"), 
                  "La Caducidad"), "Id");
            return false;
        }
        contexto.Caducidad.Remove(caducidad);
        await contexto.SaveChangesAsync();
        return true;
    }
    
    public IQueryable<Caducidad> ObtenerIQueryable()
    {
        return caducidadDAO.ObtenerIQueryable();
    }
}
```

{% endcode %}

### Creando nuestro Objeto Query

Vamos a crear nuestro objeto **Query** el cual contiene todos los servicios que vamos a exponer de consulta. Crearé una carpeta **GraphQL** y dentro una carpeta **HotChocolate**  (para diferenciar con la otra librería de grapqhl)

Agrega una función **GetCaducidad** que reciba como parámetro el contexto en este caso es CaducaContext con el atributo \[Service] el cual realizará el dependency injection y también el LocService para los mensajes de error

Por último agregamos nuestra clase CaducidadDAO y llamamos a la función ObtenerIQueryable.

Para poder seleccionar solo algunos campos de la tabla agregamos \[**UseProjection**]

Para filtrar información agregamos \[**UseFiltering**] y agregamos  \[**UseSorting**] para ordenar

{% code title="Query.cs" %}

```csharp
using System.Linq;
using CaducaRest.DAO;
using CaducaRest.Models;
using CaducaRest.Resources;
using HotChocolate;
using HotChocolate.Data;
using HotChocolate.Types;

namespace CaducaRest.GraphQL.HotChocolate;

/// <summary>
/// Querys for grapqhl
/// </summary>
public class Query
{
    [UseProjection]
    [UseFiltering]
    [UseSorting]
    public IQueryable<Caducidad> GetCaducidad([Service] CaducaContext caducaContext, 
                                              [Service] LocService locService) 
    {
        CaducidadDAO caducidadDAO = new CaducidadDAO(caducaContext, locService);
        return caducidadDAO.ObtenerIQueryable();
    }
}
```

{% endcode %}

Puedes ver a continuación el link oficial <https://chillicream.com/docs/hotchocolate/get-started>

También puedes ver la dotneconf donde se ve una introducción

<https://www.youtube.com/watch?v=GBvTRcV4PVA&list=PLdo4fOcmZ0oVFtp9MDEBNbA2sSqYvXSXO&index=29>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://abi.gitbook.io/net-core/6.3-agregar-graphql/6.3.3-creando-el-query.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
