Series: GraphQL with .NET & React, From Zero to Production
Welcome to this comprehensive GraphQL tutorial series! By the end of these 5 articles, you'll have a solid understanding of GraphQL and hands-on experience building a full-stack application with React and .NET.
Get your code here: GitHub
This is the series that takes you from GraphQL basics to advanced patterns.
Part 1: Foundations & Library Backend
Part 2: Query (Arguments, Aliases & Fragments)
Part 4: Real-Time Data with web sockets
Part 5: Advanced Patterns (Pagination, Errors, JWT & Testing)
Part 3: Mutations (Create, Update & Delete)
Welcome to Part 3! We've mastered reading data with queries. Now it's time to learn how to modify data with mutations - the GraphQL way of creating, updating, and deleting records.
Where We Left Off
We can now write sophisticated queries with arguments, variables, fragments, and filtering. Our Library app displays books and authors beautifully. But what about adding new books or writing reviews? That's where mutations come in!
What Are Mutations?
Mutations are GraphQL operations that change data on the server. If queries are like SELECT in SQL, mutations are like INSERT, UPDATE, and DELETE.
Why "Mutation"?
The name comes from the concept of "mutating" (changing) data. While queries just read data, mutations cause side effects - they change something on the server.
Queries vs Mutations
| Aspect | Query | Mutation |
|---|---|---|
| Purpose | Read data | Modify data |
| Side effects | None | Expected |
| Execution | Can run in parallel | Run one at a time, in order |
| Keyword | query (or omit) | mutation (required) |
| Analogy | SELECT / GET | INSERT/UPDATE/DELETE / POST/PUT/DELETE |
Why Sequential Execution Matters
Imagine these two mutations:
Create a user
Create a post for that user
If they ran in parallel, #2 might run before #1 completes, failing because the user doesn't exist yet!
GraphQL guarantees mutations run in the order you write them.
Mutation Syntax
Basic Structure
mutation OperationName {
mutationField(arguments) {
# Fields to return after the mutation
}
}Example:
mutation CreateBook {
addBook(input: { title: "New Book", authorId: 1, ... }) {
book {
id
title
}
}
}With Variables (Recommended)
mutation CreateBook($input: AddBookInput!) {
addBook(input: $input) {
book {
id
title
}
error
}
}Variables JSON:
{
"input": {
"title": "New Book",
"authorId": 1,
"publishedYear": 2024,
"price": 19.99,
"pageCount": 200
}
}Input Types
What Are Input Types?
Input types are special GraphQL types used for mutation arguments. They group related parameters together.
Without input type:
mutation {
addBook(
title: "New Book",
description: "A great book",
isbn: "123-456",
publishedYear: 2024,
genre: "Fiction",
price: 19.99,
pageCount: 300,
authorId: 1
) { ... }
}With input type (cleaner!):
mutation {
addBook(input: {
title: "New Book",
description: "A great book",
isbn: "123-456",
publishedYear: 2024,
genre: "Fiction",
price: 19.99,
pageCount: 300,
authorId: 1
}) { ... }
}Defining Input Types (Backend)
In C#, input types are typically records:
// GraphQL/Types/InputTypes.cs
// 'record' is a C# feature for immutable data classes
// It automatically generates constructor, equality, etc.
public record AddBookInput(
string Title, // Required - no '?'
string? Description, // Optional - has '?'
string? Isbn,
int PublishedYear,
string? Genre,
decimal Price,
int PageCount,
int AuthorId,
List<int>? CategoryIds // Optional list
);
public record UpdateBookInput(
int Id, // Required - which book to update
string? Title, // All optional - only update provided fields
string? Description,
string? Isbn,
int? PublishedYear,
string? Genre,
decimal? Price,
int? PageCount,
bool? IsAvailable
);Input Types in Schema
HotChocolate generates this schema:
input AddBookInput {
title: String!
description: String
isbn: String
publishedYear: Int!
genre: String
price: Decimal!
pageCount: Int!
authorId: Int!
categoryIds: [Int!]
}
Notice:
inputkeyword (nottype)Can't have resolvers (unlike regular types)
Can only contain scalars or other input types
Creating Data (Add Mutations)
Backend Implementation
// GraphQL/Mutations/Mutation.cs
public class Mutation
{
public async Task<AddBookPayload> AddBook(
LibraryDbContext context, // Injected by HotChocolate
[Service] ITopicEventSender eventSender, // For subscriptions (Part 4)
AddBookInput input) // The input from GraphQL
{
// 1. Validate: Check if author exists
var authorExists = await context.Authors
.AnyAsync(a => a.Id == input.AuthorId);
if (!authorExists)
{
// Return error in payload instead of throwing
return new AddBookPayload(null, "Author not found");
}
// 2. Create the entity
var book = new Book
{
Title = input.Title,
Description = input.Description,
Isbn = input.Isbn,
PublishedYear = input.PublishedYear,
Genre = input.Genre,
Price = input.Price,
PageCount = input.PageCount,
AuthorId = input.AuthorId
};
// 3. Save to database
context.Books.Add(book);
await context.SaveChangesAsync();
// 4. Handle categories if provided
if (input.CategoryIds?.Any() == true)
{
var bookCategories = input.CategoryIds
.Select(categoryId => new BookCategory
{
BookId = book.Id,
CategoryId = categoryId
});
context.BookCategories.AddRange(bookCategories);
await context.SaveChangesAsync();
}
// 5. Publish event for subscriptions (covered in Part 4)
await eventSender.SendAsync("OnBookAdded", book);
// 6. Return success payload
return new AddBookPayload(book, null);
}
}
// Payload type - contains result OR error
public record AddBookPayload(Book? Book, string? Error);GraphQL Mutation
mutation AddBook($input: AddBookInput!) {
addBook(input: $input) {
book {
id
title
description
publishedYear
author {
name
}
}
error
}
}React Implementation
import { useMutation, gql } from '@apollo/client';
const ADD_BOOK = gql`
mutation AddBook($input: AddBookInput!) {
addBook(input: $input) {
book {
id
title
author { name }
}
error
}
}
`;
function AddBookForm() {
const [form, setForm] = useState({
title: '',
description: '',
publishedYear: 2024,
genre: '',
price: 0,
pageCount: 0,
authorId: 0,
});
// useMutation returns [mutateFunction, { loading, error, data }]
const [addBook, { loading, error }] = useMutation(ADD_BOOK, {
// Refetch books list after adding
refetchQueries: ['GetBooks'],
// Called when mutation completes
onCompleted: (data) => {
if (data.addBook.error) {
alert(`Error: ${data.addBook.error}`);
} else {
alert(`Book "${data.addBook.book.title}" created!`);
// Reset form...
}
}
});
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
await addBook({
variables: { input: form }
});
};
return (
<form onSubmit={handleSubmit}>
<input
value={form.title}
onChange={(e) => setForm({...form, title: e.target.value})}
placeholder="Title"
required
/>
{/* More form fields... */}
<button type="submit" disabled={loading}>
{loading ? 'Adding...' : 'Add Book'}
</button>
{error && <p className="error">Network error: {error.message}</p>}
</form>
);
}

Join the conversation! Your thoughts help the community grow.