Search code examples
c#graphqlhotchocolate

HotChocolate not mapping models properly to type


Hotchocolate does not appear to have mapped one of my models properly. I have this product search model:

public class ProductSearchResponseModel : ISearchResult<SimpleProductViewModel>
{
    public string Identifier { get; set; }
    public Dictionary<string, List<FacetModel>> Facets { get; set; }
    public bool HasMoreResults { get; set; }
    public long Total { get; set; }
    public List<SimpleProductViewModel> Items { get; set; }
}

As you can see there, it has a FacetModel which looks like this:

public class FacetModel
{
    public object Value { get; set; }
    public object From { get; set; }
    public object To { get; set; }
    public long? Count { get; set; }
}

For some reason, this is not being mapped properly by hotchololate:

enter image description here

I have created a type and registered it like this:

public class FacetType: ObjectType<FacetModel>
{
}

public static void AddGraphQLServices(this IServiceCollection services)
{
    services
        .AddGraphQLServer()
        .AddType<FacetType>()
        .AddQueryType<Query>();
}

But if I look at the docs, it looks like this:

enter image description here

Does anyone know what is happening with this?


Solution

  • This is because the type of your properties are object. Hot Chocolate doesn't know how to handle object, since there's no concept of an object in GraphQL. There's the object type, yes, but it has a known set of fields, which the object does not have - it could be anything.

    That being said, there's an AnyType in Hot Chocolate. You could annotate your object as an AnyType and then retrieve the actual value in your resolvers.

    public class FacetModel
    {
        [GraphQLType(typeof(AnyType))]
        public object Value { get; set; }
    }
    

    The AnyType only works for scalars (string, int, ...) and IDictionary though. If these objects need to support different object types, I'd suggest using unions.

    Learn more about the AnyType

    Learn more about unions