0

我正在尝试使用 .net 核心的 Hot Chocolate 库来实现标准的 GraphQL 实现,其中用于读取数据的解析器属于根 Query 对象。像这样:

{
  Query {
    GetTodo {
      Id
    }
  }
}

这是我试图遵循文档所做的,但它没有按我预期的那样工作:

启动.cs

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

查询.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> {
        
    }
}

我做错了什么?

4

1 回答 1

1

你需要稍微改变一下:

query {
  todo {
    id
  }
}

启动.cs

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

查询.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();
    }        
}

用 HotChocolate 10.5.2 测试

解决方案的来源 - ChilliCream 博客,HotChocolate 10.3.0 文章,TypeAttributes部分。

于 2020-09-03T14:40:24.690 回答