In EF Core 10, how is an OrderStatus enum property stored by default, and how do you store its name with HasConversion<string>()?
answer
- default: the enum's underlying number
- HasConversion<string>()
- EnumToStringConverter is built in
- HasMaxLength bounds the column
- ConfigureConventions for every OrderStatus
basics
~20 sEF Core stores an enum as its underlying integer type by default, so a plain OrderStatus becomes an int column. HasConversion<string>() picks the built-in enum-to-string converter and the column holds names such as "Shipped"; add HasMaxLength so the column is not unbounded.
solid answer
~30 sWith no configuration EF Core maps `OrderStatus` to its underlying integer type, so `Shipped` is stored as its number. `Property(o => o.Status).HasConversion<string>()` tells EF Core the provider type is `string`, and it selects the built-in `EnumToStringConverter` for you; a hand-written `HasConversion(v => v.ToString(), v => Enum.Parse<OrderStatus>(v))` does the same. Giving the column a string store type, `HasColumnType("varchar(20)")` or `[Column(TypeName = "varchar(20)")]`, also switches to names. With `HasConversion<string>()`, add `HasMaxLength(20)` as well, otherwise the column is unbounded text. For every `OrderStatus` property at once, use `configurationBuilder.Properties<OrderStatus>().HaveConversion<string>()` in `ConfigureConventions`. Queries keep working: `Where(o => o.Status == OrderStatus.Shipped)` compares the column with `'Shipped'`.
code
csharp · 12 linespublic enum OrderStatus { Pending, Paid, Shipped, Delivered, Cancelled }
modelBuilder.Entity<Order>()
.Property(o => o.Status)
.HasConversion<string>()
.HasMaxLength(20);
// or for every OrderStatus property in the model:
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
=> configurationBuilder.Properties<OrderStatus>()
.HaveConversion<string>()
.HaveMaxLength(20);go deeper
Recall the default numeric mapping and the one call, HasConversion<string>(), that stores names instead.
Explain why the generic argument is the provider type, how EF Core picks EnumToStringConverter, and why HasMaxLength belongs on the same property.
Set the rule once per enum in ConfigureConventions, and plan renames and the EF Core 8 JSON default when upgrading.
Agree a team-wide enum storage convention, numbers or names, and the data-migration discipline renames then require.
## The default mapping An `enum` in C# is a named set of values over an integer type: `enum OrderStatus { Pending, Paid, Shipped, Delivered, Cancelled }` is backed by `int`, and `Shipped` is the number 2. EF Core has always mapped enums to a **numeric column of the underlying type** by default: an `int` column for this enum, a smaller integer column for an enum declared `: byte` or `: short`. No configuration is needed and nothing is written as text. ## Switching to names Many teams prefer the column to hold `'Shipped'` rather than `2`, so the data reads on its own in a SQL console or a report. EF Core offers several ways to say so, and they produce the same result: 1. **`HasConversion<string>()`** in `OnModelCreating`. The generic argument is the *provider* type; EF Core sees an enum mapped to `string` and picks its built-in `EnumToStringConverter`. 2. **An explicit converter**: `HasConversion(v => v.ToString(), v => Enum.Parse<OrderStatus>(v))`, or a `ValueConverter<OrderStatus, string>` instance passed to `HasConversion`. 3. **A string column type**: `HasColumnType("varchar(20)")` or `[Column(TypeName = "varchar(20)")]` on the property. EF Core notices that an enum is going into a string column and applies the same conversion. 4. **Model-wide**, in `ConfigureConventions`: `configurationBuilder.Properties<OrderStatus>().HaveConversion<string>()` covers every `OrderStatus` property in every entity. ## Column facets still apply A converter changes the provider type, and the usual facets then apply to that type. Without a length, a string property becomes an unbounded column (`nvarchar(max)` on SQL Server, `text` on PostgreSQL). Chain the facets after the conversion: - `HasMaxLength(20)` bounds the column to the longest name you expect; - `IsUnicode(false)` asks for a non-Unicode column where the provider has one; - the same facets are available in `ConfigureConventions` (`HaveMaxLength`, `AreUnicode`). ## Queries and parameters The converter is part of the model, so EF Core applies it to constants and parameters as well as to column values: - `Where(o => o.Status == OrderStatus.Shipped)` compares the column with `'Shipped'`. - `Where(o => statuses.Contains(o.Status))` sends the names, not the numbers. - Materializing a row parses the name back into the enum. The built-in converter also accepts a different letter case or a numeric string, but a name that matches no member throws an `InvalidOperationException` at read time. Two consequences follow from storing names. Renaming an enum member changes what is written from then on, so rows that still hold the old name need a data migration in the same release. And `OrderBy(o => o.Status)` now sorts alphabetically by name rather than by the numbers in the enum declaration. ## Nullable and flags enums - A nullable `OrderStatus?` maps to a nullable column. EF Core never passes `null` to a value converter, so the same `HasConversion<string>()` serves nullable and non-nullable properties alike. - A `[Flags]` enum, such as the hardware options on a cabinet (`Drawers | SoftClose | Lock`), is better left numeric. EF Core translates `HasFlag` to a bitwise AND on the column, which only makes sense on a number; a name column would hold a comma-separated list that no index or operator understands. - `o.Status.ToString()` in a projection is translated too: a `CASE` over the members for a numeric column, a plain read for a name column. ## Enums inside JSON documents Enums inside a JSON-mapped type follow the same rule as columns. EF Core 7 wrote them into JSON documents as strings, but **EF Core 8 changed the default to numbers**, so that values in a document compare correctly with values in ordinary columns and parameters. Code upgraded from EF Core 7 that relied on string values inside JSON needs `HasConversion<string>()` on that property, or the `ConfigureConventions` rule above, to keep its documents as they were. ## Choosing | Store as | Good for | Watch out for | |---|---|---| | number (default) | compact, fast, safe to rename members | reports need a lookup to read the value | | name (`HasConversion<string>()`) | readable data, safe to reorder members | renames need a data migration; set a max length | Whichever you choose, choose it once per enum type in `ConfigureConventions`, so two entities do not store the same `OrderStatus` in two different ways.
- What SQL does Where(o => o.Status == OrderStatus.Shipped) send once the property has HasConversion<string>()?The converter applies to the constant as well as the column, so the filter compares the status column with the string `'Shipped'`. Without the conversion it would compare with the number 2. The same holds for a parameter or for `Contains` over a list of statuses.
- After an upgrade from EF Core 7, enum values inside a JSON column start appearing as numbers. Why?EF Core 8 changed the default for enums mapped inside JSON documents from strings to numbers, matching how enums are stored in ordinary columns. Add `HasConversion<string>()` to that property, or `Properties<TEnum>().HaveConversion<string>()` in `ConfigureConventions`, to keep writing names.
- EF Core stores enums as their names by default.
- HasConversion<string>() needs a hand-written converter class to work.
- A filter on a converted enum compares against the number, so it needs a manual cast.
- HasConversion<string>() gives a bounded column of the right length automatically.
- Enums inside a JSON column are always written as strings.
Assumes EF Core 10; since EF Core 8 enums inside JSON documents are stored as numbers by default, where EF Core 7 wrote strings.