Developers often fall into the trap of using primitive types (int, string, Guid) for entity identifiers when using Entity Framework (EF) because it is straightforward to simply add a string or int or Guid as the ID field for an entity. The misuse of the primitive types leads to Primitive Obsession.
Primitive Obsession refers to a code smell or anti-pattern where primitive data types (such as integers, strings, booleans, etc.) are excessively used to represent domain concepts, instead of creating dedicated classes to encapsulate those concepts.
Consider this example of Primitive Obsession:
public class Person{public Guid Id { get; set;}public string FirstName { get; set; }public string LastName { get; set; }public string EmailAddress { get; set; }/// ... more stuff}public class Customer{public Guid Id { get; set;}public string Name { get; set; }/// ... more stuff}
The Guid Id value of a Person entity can easily be mistaken or used as the Guid Id value of a Customer entity because there is no strong typing or encapsulation to prevent these two different entity ID types from being used interchangeably.
Primitive Obsession can be witnessed on almost any domain concept, not just IDs (e.g. EmailAddress, PhoneNumber, Currency). To combat Primitive Obsession, we should consider creating meaningful and domain-specific classes to represent our concepts. By encapsulating related data and behavior into these classes, we can improve our code readability, maintainability, and flexibility. See Do you know when to use value objects? for examples of replacing data with Value Objects.
Using Strongly Typed IDs we can avoid the anti-pattern and clearly represent our domain entity specific identifiers.
There are two good ways to create them in C#: hand-written readonly record struct types, or Vogen, a source generator that writes the boilerplate for you.
C# 9 added record (for one line declarations), and C# 10 added record struct (for better performance - see below), so we can declare strongly typed IDs very succinctly. With records we no longer need to implement or override equality operators - they are automagically generated for us by the compiler.
For example:
public readonly record struct PersonId(Guid Value);public readonly record struct CustomerId(Guid Value);public class Person : BaseEntity{public PersonId Id { get; set;}public string FirstName { get; set; }public string LastName { get; set; }public string EmailAddress { get; set; }/// ... more stuff}public class Customer : BaseEntity{public CustomerId Id { get; set;}public string Name { get; set; }/// ... more stuff}
Voilà! Now we have strongly typed IDs on our Person and Customer entities and no way for anyone to get the values confused or misuse them.
records are immutable by default, but record structs are not. Adding the readonly modifier regains the immutability, and any code that tries to change the ID value fails to compile.
The weakness of a plain record struct is that anyone can still create an invalid ID. new PersonId(), default(PersonId) and new PersonId(Guid.Empty) all compile, and every serializer (JSON, EF, Dapper, ASP.NET model binding) needs its own converter.
To enable the correct serialization of Strongly Typed IDs we need to add some configuration code to our EF Entities so that EF knows how to convert between the Primitive type and the Strongly Typed ID values.
Here is one way to specify the configuration:
public class PersonConfiguration : IEntityTypeConfiguration<Person>{public void Configure(EntityTypeBuilder<Person> builder){// Primary Keybuilder.HasKey(e => e.Id);// Configuration for converting the `id` property To that will be stored in the database and From the primitive value (e.g. GUID, int, string) back into a strongly typed Id:builder.Property(e => e.Id).HasConversion(// from Strong ID to Primitive valueid => id.Value,// from Primitive value to Strong IDguidValue => new PersonId(guidValue))// enable the primitive value to be auto-generated when adding (SaveChanges) new entities to the database (only works from EF Core 7 onwards).ValueGeneratedOnAdd();}}
Another slightly cleaner looking approach could be to use a ValueConverter:
public class PersonConfiguration : IEntityTypeConfiguration<Person>{public void Configure(EntityTypeBuilder<Person> builder){var converter = new ValueConverter<PersonId, Guid>(id => id.Value,guidValue => new PersonId(guidValue));builder.HasKey(e => e.Id);builder.Property(e => e.Id).HasConversion(converter).ValueGeneratedOnAdd();}}
Vogen (Value Object Generator) is a source generator and set of Roslyn analyzers. You declare a partial type with an attribute, and Vogen generates the constructor, equality, ToString, and the converters at compile time.
[ValueObject<Guid>]public readonly partial struct CustomerId;var id = CustomerId.From(Guid.CreateVersion7());
On top of what a readonly record struct gives you, Vogen adds:
new CustomerId() (VOG010) and default(CustomerId) (VOG009) into build errors, so your code can only create an ID through From or TryFrom. An ID can still arrive uninitialized (e.g. a JSON body missing the property), but it throws as soon as its value is readValidate method, and From throws (or TryFrom returns false) for bad inputTypeConverter support are on by default, so IDs serialize as plain values in APIs and route parameters. EF Core, Dapper, Newtonsoft.Json and others are opt-inreadonly record struct (see the benchmarks below)[ValueObject<Guid>]public readonly partial struct CustomerId{private static Validation Validate(Guid input) =>input == Guid.Empty ? Validation.Invalid("CustomerId cannot be empty") : Validation.Ok;}
Instead of writing a ValueConverter per ID, declare a marker class that lists your IDs, then register all of them as EF Core conventions in one line:
[EfCoreConverter<CustomerId>][EfCoreConverter<PersonId>]internal sealed partial class VogenEfCoreConverters;public class ApplicationDbContext : DbContext{protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder){base.ConfigureConventions(configurationBuilder);configurationBuilder.RegisterAllInVogenEfCoreConverters();}}
This keeps the EF converters in the Infrastructure layer, so the Domain project only references Vogen and not EF Core.
Check out the SSW Clean Architecture template, which uses Vogen for all of its strongly typed IDs.
As mentioned earlier, we could use record or record struct to succinctly describe our strongly typed IDs.
However, when using record there is a performance penalty we pay as pointed out by Dan Patrascu on his CodeWrinkles YouTube video Stop Using Records As Strongly Typed IDs!.
Dan suggests to use struct or class instead because generating 10,000 strongly typed Ids is 4x faster compared to using record.
However, class and struct are more verbose and require that we implement the Equals and GetHashCode overrides manually!
Dan unfortunately missed out a benchmark for record struct. We wrote our own benchmarks similar to Dan's, and added Vogen. Each benchmark creates 10,000 IDs and passes them to a method. We ran them with BenchmarkDotNet v0.16.0-preview.2 on .NET 11.0.0 and Vogen 8.0.7 (macOS 27.2.1, Apple M4 Pro):
| Method | Mean | Error | StdDev | Gen0 | Allocated |
|---|---|---|---|---|---|
ReadonlyRecordStructId | 4.909 μs | 0.0291 μs | 0.0272 μs | 0 | 0 B |
StructId | 4.934 μs | 0.0322 μs | 0.0302 μs | 0 | 0 B |
VogenId | 4.936 μs | 0.0193 μs | 0.0181 μs | 0 | 0 B |
RecordId | 27.847 μs | 0.0469 μs | 0.0366 μs | 38.2385 | 320,000 B |
SealedRecordId | 28.737 μs | 0.3960 μs | 0.3510 μs | 38.2385 | 320,000 B |
ClassId | 29.495 μs | 0.4366 μs | 0.3870 μs | 38.2385 | 320,000 B |
Figure: Struct-based IDs (readonly record struct, Vogen and struct) are about 6x faster than class-based IDs and allocate nothing
The struct-based options are effectively tied. readonly record struct and Vogen give us the performance of struct without needing to manually implement the equality checks.
Check out the StronglyTypedIdsBenchmarks repo on GitHub to run the benchmarks yourself.
Never use class or record for strongly typed IDs - they allocate on every ID and are ~6x slower.
readonly record struct, plus validation, analyzers that block invalid IDs, and generated EF Core and JSON convertersreadonly record struct - A good choice when you can't take a dependency on a source generator// Vogen[ValueObject<Guid>]public readonly partial struct UserId;// No dependenciespublic readonly record struct UserId(Guid Value);