In GraphQL all types are nullable by default. In the first version of GraphQL non-null fields were even not supported at all(!).
There is a good reason for this; evolvability of your API. Non-nullable fields make it hard to change your contract. Switching from a non-nullable to a nullable field will always be a breaking change. This explains why GraphQL makes every type nullable by default, and you have to explicitly mark a field as non-null by adding the bang character (!
) to your schema definition.
When you are using GraphQL.NET, the principles above still apply but the library follows some different rules to mark a field as nullable or not. For structs (integers, booleans, …) GraphQL.NET will mark them as not-null by default. You even have to explicitly mark them as nullable(see this post: https://bartwullems.blogspot.com/2018/11/graphqldotnetnullable-types-nullable.html). For all other types the rules above are followed and every type is nullable by default.
If you don’t want this, you have to wrap your GraphQL.NET type in a NonNullGraphType wrapper.
Here is a example for a single type:
public ProductType() | |
{ | |
Field(m => m.Id, type : typeof(NonNullGraphType<IdGraphType>)); | |
Field(d => d.Description); //--> Nullable | |
Field(d => d.Category, type:typeof(NonNullGraphType<CategoryType>)); | |
} |
This will generate the following schema:
type ProductType { | |
id: ID! | |
description: String | |
category: CategoryType! | |
} |
And also an example for a list:
public ProductType() | |
{ | |
Field(m => m.Id, type : typeof(NonNullGraphType<IdGraphType>)); | |
Field(d => d.Description); //--> Nullable | |
Field<NonNullGraphType<ListGraphType<SupplierType>>>("suppliers"); | |
} |
This will generate the following schema:
type ProductType { | |
id: ID! | |
description: String | |
suppliers: [SupplierType]! | |
} |
More information: