Developer knowledge network · moderated exchange

UnreliableCode қауымдастығы

Әзірлеушілерді зерттеу, кері инженерия және кодтау қауымдастығы

Knowledge indexТірі
4Categories
919Threads
2.8KЖазбалар
Tutorial

Designing Strongly Typed IDs with readonly record struct to prevent entity ID bugs in C# [StackOverflow Architecture Guide]

generic_math_geek
C# 11 Math Guru
MEMBER
Өкіл: 138
Қосылу күні: Jul 2021
Хабарламалар: 10
Рахмет: 88
1 ай бұрын · Jul 12, 2026 2:44 PM
#1

Why using raw int or Guid for entity IDs leads to subtle bugs in large applications:

If a method accepts void Assign(int userId, int orderId), accidentally swapping Assign(orderId, userId) compiles with zero warnings but corrupts database relationships.

Strongly Typed IDs:

CSHARP
public readonly record struct UserId(Guid Value);
public readonly record struct OrderId(Guid Value);

public void Assign(UserId user, OrderId order) { /* Type-Safe! */ }

readonly record struct has 0 heap allocation overhead (compiles to a raw Guid on the stack), provides value equality, and turns ID parameter mix-ups into hard compile-time errors!

roslyn_source_gen
Roslyn Compiler Dev
MEMBER
Өкіл: 120
Қосылу күні: Feb 2020
Хабарламалар: 12
Рахмет: 75
1 ай бұрын · Jul 12, 2026 7:58 PM
#2

Strongly typed IDs prevent entire classes of domain model bugs. Works seamlessly with EF Core Value Converters as well.

dotnet_runtime_architect
.NET Core Specialist
MEMBER
Өкіл: 103
Қосылу күні: Apr 2018
Хабарламалар: 40
Рахмет: 24
1 ай бұрын · Jul 13, 2026 4:50 AM
#3

The zero-overhead abstraction of readonly record struct makes this a no-brainer for Domain-Driven Design (DDD).