In this lesson, you will learn how to control whether your C# enums are stored as meaningful text strings or performance-oriented integers within your database schema.
By default, Entity Framework Core maps enums to their underlying integer values (e.g., 0, 1, 2). While efficient, this can make debugging database tables difficult because you are left staring at numbers rather than human-readable values. EF Core gives us two primary ways to configure how these map to our database.
Storing as Integers (Default)
If you are satisfied with integer storage, EF Core handles this automatically. However, you can be explicit using the Fluent API inside your OnModelCreating method:
modelBuilder.Entity<Order>()
.Property(o => o.Status)
.HasConversion<int>();
Storing as Strings
To improve readability in database tools (like SQL Server Management Studio), you can store the enum as a string. EF Core performs a "Value Conversion" behind the scenes to turn the enum member name (e.g., Shipped) into its string equivalent ("Shipped") before saving it to the table:
modelBuilder.Entity<Order>()
.Property(o => o.Status)
.HasConversion<string>();
Which should you choose?
- Use
intif you expect to rename your enum members often in your C# code. If you change a name, an integer-based database column remains unaffected, whereas a string-based column would fail to match the new name, causing data retrieval errors. - Use
stringif you need the database to be "self-documenting." This makes it much easier for data analysts or administrators to query the database directly without needing to cross-reference your source code to know what3represents.
When using string mapping, be aware that it occupies more storage space than an integer. Additionally, if you decide to rename an enum member, you will need to perform a database migration to update the existing text values in your table to match the new name, or your application will throw an exception when trying to map the old string back into your enum.
Key Takeaway: You can balance database readability and code maintainability by choosing between integer storage for flexibility or string storage for clarity using the Fluent API HasConversion method.