1

我只是想建立一些基本的例子。我想“代码优先”,我需要 C# 编译器告诉我哪里出错了。

如果我查看 https://chillicream.com/docs/hotchocolate/v10/schema/object-type/

有一个例子

type Person {
  id: Int!
  name: String!
  friends: [Person]
}

据称这是此 C# 代码的结果

public class PersonType
    : ObjectType<Person>
{
    protected override void Configure(IObjectTypeDescriptor<Person> descriptor)
    {
        descriptor.Field(t => t.Name).Type<NonNullType<StringType>>();
        descriptor.Field("friends")
            .Type<ListType<NonNullType<StringType>>>()
            .Resolver(context =>
                context.Service<IPersonRepository>().GetFriends(
                    context.Parent<Person>().Id));
    }
}

好的,所以 id 丢失了,但是文档继续解释说热巧克力会填补空白(我不喜欢这种东西......但把它放在一边)。然后我们有“name”,它是一个字符串,这似乎对应于

.Type<NonNullType<StringType>>()

好吧,那是可信的,“朋友”虽然看起来很奇怪。“类型”是

.Type<ListType<NonNullType<StringType>>>()

我会期待一些更明显映射到“[Person]”的东西

医生错了吗?还是我的理解错了?

4

1 回答 1

2

首先,是的,那里的文档是错误的。将在此 PR 中修复:https ://github.com/ChilliCream/hotchocolate/pull/2890

正确的代码是

public class PersonType
    : ObjectType<Person>
{
    protected override void Configure(IObjectTypeDescriptor<Person> descriptor)
    {
        descriptor.Field(t => t.Name).Type<NonNullType<StringType>>();
        descriptor.Field("friends")
            .Type<ListType<NonNullType<PersonType>>>()
            .Resolver(context =>
                context.Service<IPersonRepository>().GetFriends(
                    context.Parent<Person>().Id));
    }
}

好的,所以 id 丢失了,但是文档继续解释说热巧克力会填补空白(我不喜欢这种东西......但把它放在一边)。

如果您不喜欢它,您可以部分关闭它。如果未设置,HotChocolate 将始终尝试从 .NET 推断类型。但是,如果您想禁用属性推断,您可以通过两种方式执行此操作。

  1. 全局禁用它
schemaBuilder.ModifyOptions(x => x.DefaultBindingBehavior = BindingBehavior.Explicit)

  1. 按类型禁用它
public class PersonType
    : ObjectType<Person>
{
    protected override void Configure(IObjectTypeDescriptor<Person> descriptor)
    {
         descriptor.BindFieldsExplicitly();
    }
}
于 2021-01-17T18:04:15.187 回答