Documentation

Development

Using Database

Let's modify the handler we created in previous steps to use the real database. ShipDotnet.Handlers/Handlers/Products/Queries/GetProductById.cs :

namespace ShipDotnet.Handlers
{
	public static class GetProductById
	{
		public class Query : IQuery<IHandlerResponse<Response>>
		{
			public int Id { get; set; }
		}

		public record Response(ProductModel Product);

		public record ProductModel(int Id, string Name, string? Description);

		public class Handler : QueryHandler<Query, Response>
		{
			public Handler(IHandlerContext context) : base(context) { }

			public override async Task<IHandlerResponse<Response>> ExecuteAsync(Query query, CancellationToken ct)
			{
				var product = await DbContext.Products
					.Where(x => x.Id == query.Id)
					// .Select(x => new ProductModel(x.Id, x.Name, x.Description)) // you can also directly project to the model
					.SingleOrDefaultAsync(ct);

				if (product is null)
				{
					return Error("Product not found");
				}

				var model = new ProductModel(product.Id, product.Name, product.Description);

				return Success(new Response(model));
			}
		}
	}
}

You can now run the API and test the endpoint from Swagger: http://localhost:5000/swagger/index.html