GraphQL C#
Install package
dotnet add package graphiql --version=2.0.0
dotnet add package GraphQL --version=4.6.1
dotnet add package GraphQL.Server.Transports.AspNetCore.SystemTextJson --version=5.2.2
dotnet add package GraphQL.Server.Ui.GraphiQL --version=5.2.2
Category Type
public class CategoryType : ObjectGraphType{
public CategoryType(){
Field(p => p.CategoryId, type: typeof(IdGraphType)).Description("Id Property for Category object");
Field(p => p.CategoryName, type: typeof(StringGraphType)).Description("Name Property for Category object");
}
}
Category Input Type
public class CategoryInputType : InputObjectGraphType{
public CategoryInputType(){
Name = "CategoryInputType";
Field<StringGraphType>("CategoryName");
}
}
Category Query
public class CategoryQuery : ObjectGraphType<Category>{
public CategoryQuery(CategoryRepository repository){
Field<ListGraphType<CategoryType>(
name: "categories",
resolve: context => repository.GetCategories());
Field<CategoryType>(
name: "category",
arguments: new QueryArguments(
new QueryArgument<NonNullGraphType<IntGraphType>>{ Name = "id", Description = "Category Id"}),
resolve: p => repository.GetCategory(p.GetArgument<short>("id")));
}
}
Category Mutation
public class CategoryMutation : ObjectGraphType{
public CategoryMutation(CategoryRepository repository){
Field<CategoryType>(
name: "addCategory",
arguments: new QueryArguments(
new QueryArgument<NonNullGraphType<CategoryInputType>>{
Name = "category",
Description = "Category input parameter"}
),
resolve: p => {
var obj = p.GetArgument<Category>("category");
if(obj != null){
return repository.Add(obj);
}
return -1;
});
}
}
App Schema
public class AppSchema : Schema{
public AppSchema(CategoryQuery query, CategoryMutation mutation) =>
(Query, Mutation) = (query, mutation);
}
Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddGraphQL().AddSystemTextJson();
builder.Services.AddControllers();
var app = builder.Build();
app.UseGraphQL();
app.UseGraphQLGraphiQL("/ui/graphql");
app.MapControllers();