tags

strong typing

C# 9 records as strongly-typed ids - Part 2: ASP.NET Core route and query parameters

Created by Wireform from the Noun Project Using C# 9 records as strongly-typed ids
Last time, I explained how easy it is to use C# 9 record types as strongly-typed ids: public record ProductId(int Value); But unfortunately, we’re not quite done yet: there are a few issues to fix before our strongly-typed ids are really usable. For instance, ASP.NET Core doesn’t know how to handle them in route parameters or query string parameters. In this post, I’ll show how to address this issue. Model binding of route and query string parameters Let’s say we have an entity like this:

Using C# 9 records as strongly-typed ids

Created by Wireform from the Noun Project Using C# 9 records as strongly-typed ids
Strongly-typed ids Entities typically have integer, GUID or string ids, because those types are supported directly by databases. However, if all your entities have ids of the same type, it becomes pretty easy to mix them up, and use the id of a Product where the id of an Order was expected. This is actually a pretty common source of bugs. public void AddProductToOrder(int orderId, int productId, int count) { .