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).