Preforming CRUD Operations Using GraphQL In ASP.NET Core
Tags: graphql, dotnet, dotnetcore
Published: 2020-08-08 05:39:28

### Introduction
Like REST, **GraphQL** also allows the client to make changes to data that’s currently stored in the backend. In GraphQL, these changes are made using **_mutations_** which is nothing but a type of operation that allows creating, updating, and deleting data. For the read operation, we used GraphQL query type (explained in the article “[Build an API in .NET Core with GraphQL](https://dev.to/dynamicanupam/build-an-api-in-net-core-with-graphql-40lk)”), which is completely flexible, and based on the requirement that the user/client decides what data is actually needed.
 
As we know, GraphQL specifies three types that are used to perform operations of a GraphQL server.
* **_Query_** - Used for retrieving data based on needs.
* **_Mutation_** – Used for making changes to the data/entity.
* **_Subscription_** – Used for real-time updates on important events.

#### Related reads:
**[Part 1 - Build an API in .NET Core with GraphQL](https://dev.to/dynamicanupam/build-an-api-in-net-core-with-graphql-40lk)**

### Implementing GraphQL Mutation with ASP.NET Core
 
In this article, we will be going to add a mutation type that allows users to modify a tech event entity into the DB. This article is a continuation of the previous one which is mentioned in related reads.
 
First, we're going to make some changes to model and repositories which will allow inserting, updating, and deleting on tech event entity. Next, we're going to create new GraphQL types that we need in order to enable the mutation. And then we will update the schema so that mutation will be available to the client/user and then create a mutation and test is though GraphiQL UI as well as Postman.
#### Create models and add methods to the repository
Add a folder called Models into the project (which we build earlier [here](https://dev.to/dynamicanupam/build-an-api-in-net-core-with-graphql-40lk)) and add a new model called NewTechEventRequest.cs into it which basically contains properties that are required to create a new tech event and save into DB.

_NewTechEventRequest.cs_
```C#
using System;   
namespace GraphQL.API.Models  
{  
    public class NewTechEventRequest  
    {  
        public string EventName { get; set; }  
        public string Speaker { get; set; }  
        public DateTime EventDate { get; set; }  
    }  
}  
```
Now we are going to add the below 3 methods to our repository interface.

_ITechEventRepository.cs_
```C#
Task<TechEventInfo> AddTechEventAsync(NewTechEventRequest techEvent);  
Task<TechEventInfo> UpdateTechEventAsync(TechEventInfo techEvent);  
Task<bool> DeleteTechEventByIdAsync(TechEventInfo techEvent); 
```
And implement those methods into TechEventRepository.cs.
```C#
public async Task<TechEventInfo> AddTechEventAsync(NewTechEventRequest techEvent)  
{  
    var newEvent = new TechEventInfo { EventName = techEvent.EventName, Speaker = techEvent.Speaker, EventDate = techEvent.EventDate };  
    var savedEvent = (await _context.TechEventInfo.AddAsync(newEvent)).Entity;  
    await _context.SaveChangesAsync();  
    return savedEvent;  
}  
  
public async Task<bool> DeleteTechEventByIdAsync(TechEventInfo techEvent)  
{  
    _context.TechEventInfo.Remove(techEvent);  
    await _context.SaveChangesAsync();  
    return true;  
}  
  
public async Task<TechEventInfo> UpdateTechEventAsync(TechEventInfo techEvent)  
{  
    var updatedEvent = (_context.TechEventInfo.Update(techEvent)).Entity;  
    await _context.SaveChangesAsync();  
    return updatedEvent;  
}
```
#### Create GraphQL input type
Next, we're going to update the schema. To do this, create a GraphQL input type which will correspond with the NewTechEventRequest model that we just created. This is the type that we are going to send from a client as an argument to mutation.
 
Right click on GraphqlCore folder, then add a new class called TechEventInputType.cs and add below-mentioned code.
 
_TechEventInputType.cs_
```C#
using GraphQL.Types;   
namespace GraphQL.API.GraphqlCore  
{  
    public class TechEventInputType : InputObjectGraphType  
    {  
        public TechEventInputType()  
        {  
            Name = "AddEventInput";  
            Field<NonNullGraphType<StringGraphType>>("eventName");  
            Field<StringGraphType>("speaker");  
            Field<NonNullGraphType<DateGraphType>>("eventDate");  
        }  
    }  
} 
```
The TechEventInputType class derives from the InputObjectGraphType class and in the constructor, we just populate the Name property and added three fields.
 
Here:
* _InputObjectGraphType_ – used to define an input type and this is going to tell GraphQL that this is an input type.
* _NonNullGraphType_ – used to require a non-null values.
* _StringGraphType_ – used to define a string field.
* _DateGraphType_ – used to define a date field.

### Create Mutation
Create the TechEventMutation class inside the GraphqlCore folder.
_TechEventMutation.cs_
```C#
using GraphQL.API.Infrastructure.Repositories;  
using GraphQL.Types;  
using GraphQL.API.Models;  
using GraphQL.API.Infrastructure.DBContext;  
  
namespace GraphQL.API.GraphqlCore  
{  
    public class TechEventMutation : ObjectGraphType<object>  
    {  
        public TechEventMutation(ITechEventRepository repository)  
        {  
            Name = "TechEventMutation";  
  
            FieldAsync<TechEventInfoType>(  
                "createTechEvent",  
                arguments: new QueryArguments(  
                    new QueryArgument<NonNullGraphType<TechEventInputType>> { Name = "techEventInput" }  
                ),  
                resolve: async context =>  
                {  
                    var techEventInput = context.GetArgument<NewTechEventRequest>("techEventInput");  
                    return await repository.AddTechEventAsync(techEventInput);  
                });  
        }  
    }  
}
```
Inside the constructor, the name is the name of the mutation and field with the name createTechEvent, which will return the TechEventInfoType object.
 
When we create a tech event, we are going to pass an instance of an argument of type TechEventInputType, with a variable name “techEventInput” that we provide in GraphQL. The resolve action is going to execute the AddTechEventAsync method from our repository to add data into DB.
 
_TechEventSchema.cs_
```C#
Mutation = resolver.Resolve<TechEventMutation>(); 
```
Update startup.cs class and register these types into ConfigureServices that we created so far.
```C#
services.AddSingleton<TechEventInputType>();  
services.AddSingleton<TechEventMutation>();  
```
Excellent, now we are done with adding Mutation into our project. Let’s start the project, and create a tech event from GraphiQL. We will see newly added schema details once it’s loaded to the browser.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/u964qr6wftthy8dt66bx.png)

Now it’s time to test it.
 
The syntactical structure of Mutations is similar to queries, but always starts with the mutation keyword. Below is the example to create a tech event.
```graphql
mutation ($techEvent : AddEventInput!){  
  createTechEvent(techEventInput : $techEvent){  
    eventId,  
    eventName,  
    eventDate,  
    participants{  
      phone  
    }  
  }  
}  
```
Add the below variable to the Query Variables window:
```graphql
{  
  "techEvent": {  
    "eventName": "Azure Devops CI/CD Demo",  
    "speaker": "Anupam M",  
    "eventDate": "2020-12-12"  
  }  
}  
```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/zq0t2nmgba6xu6ygsekp.png)

Here, we create a tech event with an argument called techEventInput and return the eventId, eventName, eventDate, participants of that newly added event. We used a variable called “techEvent” to pass in the techEventInput argument via the Query Variables window. On the right side of GraphiQL, we can see that event creation is successful and got the newly created tech event as a response.
 
Let’s test the same using Postman. We will use the below output as an example.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/v4s0jegmm67lkgksjup7.png)

###Update Mutation
 
Whatever we did for Create tech event, we can similarly do for an update tech event.pasting. Add an additional field into TechEventMutation.cs with the name “updateTechEvent”.

```C#
FieldAsync<TechEventInfoType>(  
    "updateTechEvent",  
    arguments: new QueryArguments(  
        new QueryArgument<NonNullGraphType<TechEventInputType>> { Name = "techEventInput" },  
        new QueryArgument<NonNullGraphType<IdGraphType>> { Name = "techEventId" }),  
    resolve: async context =>  
    {  
        var techEventInput = context.GetArgument<TechEventInfo>("techEventInput");  
        var techEventId = context.GetArgument<int>("techEventId");  
  
        var eventInfoRetrived = await repository.GetTechEventById(techEventId);  
        if (eventInfoRetrived == null)  
        {  
            context.Errors.Add(new ExecutionError("Couldn't find Tech event info."));  
            return null;  
        }  
        eventInfoRetrived.EventName = techEventInput.EventName;  
        eventInfoRetrived.EventDate = techEventInput.EventDate;  
  
        return await repository.UpdateTechEventAsync(eventInfoRetrived);  
    }  
);
```
Now run the project again and test it.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/7269d11pqszw1i2z5yvv.png)

When we pass a non-existing event during an update operation, we receive an error message which is expected as we defined it.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/jqe08xzxei8d5caiqb9r.png)

###Delete Mutation
 
Similarly, add a new field for deleting an operation in the TechEventMutation.cs class and name it as “deleteTechEvent”.

```C#
FieldAsync<StringGraphType>(  
    "deleteTechEvent",  
    arguments: new QueryArguments(new QueryArgument<NonNullGraphType<IdGraphType>> { Name = "techEventId" }),  
    resolve: async context =>  
    {  
        var techEventId = context.GetArgument<int>("techEventId");  
  
        var eventInfoRetrived = await repository.GetTechEventById(techEventId);  
        if (eventInfoRetrived == null)  
        {  
            context.Errors.Add(new ExecutionError("Couldn't find Tech event info."));  
            return null;  
        }  
        await repository.DeleteTechEventByIdAsync(eventInfoRetrived);  
        return $"Tech Event ID {techEventId} with Name {eventInfoRetrived.EventName} has been deleted succesfully.";  
    }  
);
```
Let’s run the project again and test it with the below mutation request:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/mepe8tqa7dhdwpms4z1a.png)

```graphql
mutation ($techEventId:ID!){  
  deleteTechEvent(techEventId : $techEventId)  
} 
```
Query variable:
```
{  
  "techEventId": 5  
}
```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/2zm0a3r1a3fml1z50c9b.png)

Awesome, isn’t it! 

We are done with basic CRUD operations using GraphQL in ASP.NET Core.
 
**All the source code described here can be found on [GitHub](https://github.com/dynamicanupam/AspNetCoreWithGraphQL).**
 
###Conclusion
 
In this article, we discussed the input type for the mutations, created different mutation actions, and performed CRUD operations on an entity by modifying mutation requests and testing it from GraphiQL as well as Postman. I hope you learned GraphQL API implementation with .NET Core using mutation and query type so far. Happy learning!