首页 > 解决方案 > 在 v11 中进行演练时生成的奇怪架构

问题描述

我正在尝试通过一个非常简单的 graphql 服务器示例并进行选择。

https://www.blexin.com/en-US/Article/Blog/Creating-our-API-with-GraphQL-and-Hot-Chocolate-79

(没有 SQL 后端,我想了解它端到端,所以这在内存数据表中)。

我已经按照演练实现了它(某些属性,例如“[UseFiltering]”不编译,我暂时将它们注释掉)。

我的启动看起来像这样

        services.AddSingleton<IAuthorService, InMemoryAuthorService>();
        services.AddSingleton<IBookService, InMemoryBookService>();

        services.
            AddGraphQLServer().
            AddType<AuthorType>().
            AddType<BookType>().
            AddQueryType<GraphQL.Query>();

看起来很奇怪的是当我试图询问一本书的作者时

{
  books {
    title
    authorId
    price
    author { 
      name
      surname 
    }
  }
}

香蕉蛋糕流行抱怨

field author argument book of type BookInput! is required

(如果我不要求作者,那么一切都很好)

booktype 看起来像这样(根据演练)

public class BookType : ObjectType<Book>
{
    protected override void Configure(IObjectTypeDescriptor<Book> descriptor)
    {
        descriptor.Field(b => b.Id).Type<IdType>();
        descriptor.Field(b => b.Title).Type<StringType>();
        descriptor.Field(b => b.Price).Type<DecimalType>();
        descriptor.Field<AuthorResolver>(t => t.GetAuthor(default, default));
    }
}

作者解析器看起来像这样

public class AuthorResolver
{
    private readonly IAuthorService _authorService;

    public AuthorResolver([Service]IAuthorService authorService)
    {
        _authorService = authorService;
    }

    public Author GetAuthor(Book book, IResolverContext ctx)
    {
        return _authorService.GetAll().Where(a => a.Id == book.AuthorId).FirstOrDefault();
    }
}

再次,根据演练。

我基本上理解错误,但我无法理解这应该如何工作,不知何故,“书”父母必须进入 AuthorResolver 上的 GetAuthor 方法......我错过了一些魔法,或者 v11 是缺少一些魔法。

附言

我更喜欢声明性类型的表达式,而不是反身魔法......所以也许我错过了一些东西

标签: hotchocolate

解决方案


问题是我的 AuthorResolver 上的 GetAuthor 方法缺少“父”属性,以触发一些魔法......

    public Author GetAuthor([Parent]Book book, IResolverContext ctx)
    {
        return _authorService.GetAll().Where(a => a.Id == book.AuthorId).FirstOrDefault();
    }

理想情况下,我想删除这个自定义属性魔法。


推荐阅读