Skip to content

ApplyEnumAsString ​

Stores an enum property as its member name rather than its underlying number.

Entity Framework Core stores an enum as an integer by default, so inserting a member in the middle re-points every existing row at a different member with no error and no migration change. The cost of storing the name is a text column and a text comparison.

Usage ​

csharp
using AlmightyShogun.EntityFrameworkCore.ModelBuilding;

modelBuilder.ApplyEnumAsString<Order, Status>(order => order.Status);
csharp
using AlmightyShogun.EntityFrameworkCore.ModelBuilding;

modelBuilder.ApplyEnumAsString<Order, FulfilmentStage>(
    order => order.Stage,
    maxLength: 64
);
csharp
public sealed class Order
{
    public int Id { get; set; }
    public Status Status { get; set; }
    public FulfilmentStage Stage { get; set; }
}

public enum Status
{
    Pending,
    Shipped,
    Cancelled
}

public enum FulfilmentStage
{
    AwaitingPaymentConfirmation,
    ReadyForWarehousePicking,
    HandedToCarrier
}

WARNING

Renaming a member changes the stored value. Nothing in the model records member names, so a rename produces an empty migration rather than one that rewrites the rows: the UPDATE has to be written by hand.

Parameters

property: Expression<Func<TEntity, TProperty>>
The enum property to configure.

maxLength: int
The maximum stored length. Raise it when a member name is longer than the default.
Default: 32

Returns

The ModelBuilder instance with the property stored as text.

Type signature ​

csharp
public ModelBuilder ApplyEnumAsString<TEntity, TProperty>(
    Expression<Func<TEntity, TProperty>> property,
    int maxLength = 32
) where TEntity : class where TProperty : struct, Enum;

All packages are released under the MIT License.