Using variables in queries
In the previous section, we learned how to query data and modify data using GraphQL queries and mutations. In this section, we will discuss how to use variables in queries.
GraphQL allows you to use variables in queries. This is useful when you want to pass parameters to the query. We can create a query that accepts an id
parameter and returns the teacher with the specified ID. Follow these steps to create the query:
- Add a
GetTeacher()
method in theQuery
class, as follows:public async Task<Teacher?> GetTeacher(Guid id, [Service] AppDbContext context) => await context.Teachers.FindAsync(id);
The preceding code adds a
GetTeacher()
method to theQuery
class. It takes anid
parameter and returns the teacher with the specified ID. - Now, you can use the
$
sign to define a variable in the query. For example, you can use the following query to get a teacher by ID:query getTeacher($id: UUID!) { teacher(id: $id...