0

I am using HotChocolate library to work with GraphQL via .NET. I already can get all objects, that are stored in db, using this query:

query 
{
    news
    {
        title
        description
    }
}

But I need to have an opportunity, to select object with specific id like in this query:

query
{
    news(id: 5) 
    {
        title
        description
    }
}

But I'm getting the following exception

Unknown argument "id" on field "Query.news".

I use this code to get all news from database and return it to a client:

    [UseDbContext(typeof(Context.Context))]
    [UseFiltering]
    [UseSorting]
    public IQueryable<Entities.News> GetNews([ScopedService] Context.Context context)
    {
        return context.News;
    }

Also I tried to get an object by id using this code:

    [UseDbContext(typeof(Context.Context))]
    [UseFiltering]
    [UseSorting]
    public Entities.News GetNews(int id, [ScopedService] Context.Context context)
    {
        return context.News.Find(id);
    }

But I іtill have the exception when trying to get it by id

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

2 Answers2

0

With the UseFiltering attribute, this exposes a new schema "descriptor" of WHERE and you can then use this in your Graph QL query

query ($searchId: Int!)
{
    news(where: {id: {eq:  $searchId}}) 
    {
        title
        description
    }
}
variables {
    "searchId" : 1
}
Chris Hammond
  • 2,064
  • 5
  • 27
  • 53
0

The short answer: no, you cannot proceed that way.

The explanation: the attribute [UseFiltering] can be applied to something that presents a collection of items only. In the second method with 'id', you are trying to return the single entity along with [UseFiltering]. It's not possible.

So, in total, you have the following options (which all do not conform to your needs exactly):

  1. You follow the way in that answer - as for me, it is the most logically correct approach.
  2. You can add the parameter 'id' to the method GetNews but still return IQueryable containing the single element or nothing - as for me, the most non-intuitive approach because the selection by single id is logically incompatible with filtering by WHERE, results ordering and pagination.
  3. Create a separate method GetUserById returning a single element - as for me, the correct approach which is often used along with p.1.
ademchenko
  • 585
  • 5
  • 18