1 min read

EF Core has a very nice option that will allow to use enum and save in the DB char or any other type so no need to use the same type for DB, this option is a value converter.

I will tell you the steps to how to use it and you can see the full example on ShadyNagy.ApiTemplate or use this template to generate for you the full source code for the Endpoints based on Ardalis Clean Architecture.

You have UserType which will be enum

namespace ShadyNagy.ApiTemplate.Core.Entities;

public enum UserType
{
  Employee,
  Customer
}

Create UserTypeConverter

namespace ShadyNagy.ApiTemplate.Infrastructure.Data.Converters;

public class UserTypeConverter : ValueConverter<UserType, string>
{
  public UserTypeConverter()
      : base(
          coreValue => ToString(coreValue),
          efValue => FromString(efValue))
  {
  }

  private static string ToString(UserType type)
  {
    return type switch
    {
      UserType.Customer => "C",
      UserType.Employee => "E",
      _ => throw new System.NotImplementedException(),
    };
  }

  private static UserType FromString(string type)
  {
    return type.ToUpper() switch
    {
      "C" => UserType.Customer,
      "E" => UserType.Employee,
      _ => throw new System.NotImplementedException(),
    };
  }
}

Change the UserConfig class to use the UserTypeConverter

namespace ShadyNagy.ApiTemplate.Infrastructure.Data.Config;
public class UserConfiguration : IEntityTypeConfiguration<User>
{
  public void Configure(EntityTypeBuilder<User> builder)
  {
    builder
      .ToTable("Users", "Lockup")
      .HasKey(x => x.Id);

    builder
      .Property(p => p.Id)
      .HasColumnName("Id")
      .IsRequired();

    builder
      .Property(p => p.Username)
      .HasColumnName("Username")
      .HasMaxLength(DatabaseColumnsWidth.NAME)
      .IsRequired();

    builder
      .Property(p => p.Password)
      .HasColumnName("Password")
      .HasMaxLength(DatabaseColumnsWidth.NAME);

    builder
      .Property(p => p.IsActive)
      .HasColumnName("IsActive")
      .IsRequired();

    builder
      .Property(t => t.UserType)
      .HasColumnName("UserType")
      .HasMaxLength(DatabaseColumnsWidth.TYPE_ONE_CHAR)
      .HasConversion<UserTypeConverter>()      .IsRequired();

  }
}

Click here if you want to use ShadyNagy.ApiTemplate.
Feel free to comment if there are any problems or questions.

About the author

For the last decade, Shady Nagy has worked with a variety of web technologies. He is currently focused on code quality. On his day to day job, he is working as a team leader engineer. As a digital nomad, he is living where the WiFi and sun are 😎
Do you want to know more? Visit my website!