[英]How to define a nullable list with non-nullable items in a GraphQL schema using HotChocolate?
I'm using C# 10 but with nullable reference types disabled on .NET 6 and HotChocolate 12.12.0.我正在使用 C# 10,但在 .NET 6 和 HotChocolate 12.12.0 上禁用了可空引用类型。
My Query.cs
has an entry like this:我的
Query.cs
有这样一个条目:
public async Task<List<Foo>> GetFoos() { ... }
The generated GraphQL schema looks like this: foos: [Foo]
(nullable array with nullable Foo
-items)生成的 GraphQL 架构如下所示:
foos: [Foo]
(具有可为空Foo
项的可为空数组)
When I add the [GraphQLNonNullType]
attribute to the GetFoos()
method, the generated GraphQL schema looks like this: foos: [Foo!]!
当我将
[GraphQLNonNullType]
属性添加到GetFoos()
方法时,生成的 GraphQL 模式如下所示: foos: [Foo!]!
(non-nullable array with non-nullable Foo
-items) (具有不可为空的
Foo
项的不可为空数组)
What I want my schema to look like is this: foos: [Foo!]
(nullable array with non-nullable Foo
-items)我希望我的架构看起来像这样:
foos: [Foo!]
(具有不可为空的Foo
-items 的可空数组)
From what I've found (eg this answer ) this should be possible somehow.从我发现的(例如这个答案)来看,这应该是可能的。
Does HotChocolate provide any way to produce a nullable array with non-nullable items in the schema? HotChocolate 是否提供任何方法来生成具有架构中不可为空项的可为空数组?
Yes, this is possible using Hot Chocolate.是的,这可以使用热巧克力来实现。
Using annotation-based approach:使用基于注释的方法:
[GraphQLType(typeof(ListType<NonNullType<ObjectType<Foo>>>))]
public async Task<List<Foo>> GetFoos() { ... }
Using code-first approach:使用代码优先方法:
descriptor
.Field("foos")
.Type<ListType<NonNullType<ObjectType<Foo>>>>();
https://chillicream.com/docs/hotchocolate/defining-a-schema/non-null/#explicit-nullability https://chillicream.com/docs/hotchocolate/defining-a-schema/non-null/#explicit-nullability
One solution is to enable nullable reference types and then explicitly mark the list as nullable.一种解决方案是启用可空引用类型,然后将列表显式标记为可空。
Enable nullable reference types in the .csproj
file:在
.csproj
文件中启用可为 null 的引用类型:
<Nullable>enable</Nullable>
public async Task<List<Foo>?> GetFoos() { ... }
To not change this setting for the whole project (as this likely breaks stuff), the nullable directives can be used to enable this feature just in certain parts of your code:为了不更改整个项目的此设置(因为这可能会破坏内容), 可空指令可用于仅在代码的某些部分启用此功能:
#nullable enable
public async Task<List<Foo>?> GetFoos() { ... }
#nullable disable
Don't forget to disable it again, otherwise it will also affect any other code below.不要忘记再次禁用它,否则它也会影响下面的任何其他代码。
While this solves my problem for now, I would still be interested if there is a solution without enabling nullable reference types.虽然这暂时解决了我的问题,但如果有不启用可空引用类型的解决方案,我仍然会感兴趣。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.