Search code examples
c#.netgraphqlhotchocolate

Filter list elements with hot chocolate (v13) GraphQL


I'm using hot chocolate type extension and trying to filter list elements. here are my classes:

public class A
{
    public B b { get; set; }
}
public class B
{
    public string name {  get; set; }
    public List<C> c { get; set; }
}

public class C
{
    public bool isNew { get; set; }
}

query:

[UseFiltering]
public async Task<IQueryable<A>> GetA([Service] ISender sender)
{
    return await sender.Send(new GetAQuery());
}

I'm trying to filter the list elements by "isNew" (I want to be able to get only the elements with isNew = true ) the default list filters are "any, none, all, some", is there an option to add a 'where' filter to the schema definition? enter image description here

I know I can extend the B object:

[ExtendObjectType(typeof(B))]
public class BResolver
{
    public List<C> NewC([Parent] B b)
        => b.c.Where(el=>el.isNew).ToList();
}

but that's not what I'm looking for, I don't want to add fields, I want to filter on the existing field


Solution

  • Looks like you need to use some keyword in where expression. You can filter high-level elements by child element fields like this:

    query {
      a(where: { b: { c: { some: { isNew: { eq: true } } } } }) {
        b {
          name
          c {
            isNew
          }
        }
      }
    }
    

    If you need filter nested elements, you need to add [UseFiltering()] attribute:

    public class A
    {
        public B b { get; set; }
    }
    public class B
    {
        public string name { get; set; }
    
        [UseFiltering()] // This row
        public List<C> c { get; set; }
    }
    
    public class C
    {
        public bool isNew { get; set; }
    }
    

    and filter only nested objects like this:

    query {
      a {
        b {
          name
          c(where: { isNew: { eq: true } }) {
            isNew
          }
        }
      }
    }