0

I am trying to achieve a standard GraphQL implementation, using the Hot Chocolate library for .net core, where the resolvers for reading data belong to the root Query object. Like this:

{
  Query {
    GetTodo {
      Id
    }
  }
}

This is what I made trying to follow the documentation, but it doesn't work as I expect:

startup.cs

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ChocodotContext>();
            services.AddGraphQL(
                SchemaBuilder.New()
                .AddQueryType<QueryType>()
                .BindResolver<TodoQueries>()
                .Create()
            );
        }

Query.cs

using HotChocolate.Types;

namespace Queries
{
    public class QueryType : ObjectType
    {
        protected override void Configure(IObjectTypeDescriptor descriptor)
        {
            
        }
    }
}

TodoQueries.cs

using System.Threading.Tasks;
using HotChocolate;
using HotChocolate.Types;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using Models;

namespace Queries
{
    [GraphQLResolverOf(typeof(Todo))]
    [GraphQLResolverOf("Query")]
    public class TodoQueries
    {
        public async Task<Todo> GetTodo([Service] ChocodotContext dbContext) {
            return await dbContext.Todos.FirstAsync();
        }        
    }

    public class TodoQueryType : ObjectType<TodoQueries> {
        
    }
}

What am I not getting right?

Mino
  • 635
  • 10
  • 28

1 Answers1

1

You need to change it a little:

query {
  todo {
    id
  }
}

startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ChocodotContext>();
    services.AddGraphQL(serviceProvider =>
        SchemaBuilder.New()
            .AddServices(serviceProvider)
            .AddQueryType<Query>()
            .AddType<TodoQueries>()
            .Create()
    );
}

Query.cs

using HotChocolate.Types;

namespace Queries
{
    public class Query
    {

    }
}

TodoQueries.cs

[ExtendObjectType(Name = "Query")]
public class TodoQueries
{
    // Side note, no need for async/await while it returns Task<>
    //
    public Task<Todo> GetTodo([Service] ChocodotContext dbContext) {
        return dbContext.Todos.FirstAsync();
    }        
}

Tested with HotChocolate 10.5.2

Source of solution - ChilliCream Blog, HotChocolate 10.3.0 article, TypeAttributes section.

Arsync
  • 425
  • 1
  • 5
  • 15