HomeContact

Value converters in Entity Framework Code (EF Core)

By Shady Nagy
Published in dotnet
July 13, 2022
2 min read
Value converters in Entity Framework Code (EF Core)

Table Of Contents

01
Introduction
02
Using EF Core Value Converters for Enums
03
Benefits of Using Value Converters for Enums in EF Core
04
Full Example and Template
05
Troubleshooting
06
Further Reading

Introduction

In this post, we will discuss how to use Entity Framework (EF) Core value converters to store enum values in a different format in the database. This can be useful when you want to store the enum value as a char or any other type in the database. We will walk through the steps needed to implement a value converter and provide a full example using the ShadyNagy.ApiTemplate project.

Using EF Core Value Converters for Enums

Step 1: Create an Enum

First, create a UserType enum, which will be used as an example in this tutorial:

namespace ShadyNagy.ApiTemplate.Core.Entities;
public enum UserType
{
Employee,
Customer
}

Step 2: Create a Value Converter

Next, create a UserTypeConverter class to convert the enum values to strings:

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(),
};
}
}

Step 3: Configure the Value Converter in the Entity Configuration

Finally, modify 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();
}
}

Benefits of Using Value Converters for Enums in EF Core

Using value converters in EF Core for enums offers several advantages, which include:

  1. Flexibility: Value converters allow you to store enum values in various formats in the database, such as chars or strings, without changing the enum definition in your code. This flexibility makes it easy to work with different data types based on your database requirements.

  2. Readability: Storing enum values in a more human-readable format, such as strings or single characters, can improve the readability of your database records. This makes it easier for developers and database administrators to understand and maintain the data.

  3. Compatibility: Value converters enable you to work with legacy databases where enum values might be stored in different formats. By implementing custom value converters, you can map these existing formats to your code’s enums without having to change the underlying database schema.

In conclusion, EF Core value converters offer a powerful and flexible way to store and retrieve enum values in the database, making it easier to work with different data types, improving readability, and ensuring compatibility with legacy systems.

Full Example and Template

You can see the full example in the ShadyNagy.ApiTemplate GitHub repository or use the template to generate the full source code for the Endpoints based on Ardalis Clean Architecture.

To use the ShadyNagy.ApiTemplate NuGet package, click here.

Troubleshooting

If you encounter any issues while implementing EF Core value converters for enums, consider the following troubleshooting tips:

  1. Check your converter class: Ensure that your value converter class (e.g., UserTypeConverter) is correctly implemented and handles all enum values.
  2. Verify your entity configuration: Make sure you have correctly configured the value converter in your entity configuration class (e.g., UserConfiguration).
  3. Inspect database schema: Verify that the database schema is correctly generated with the expected data types for enum columns.
  4. Test your code: Perform thorough testing of your code to ensure that the enum values are properly stored and retrieved from the database.

Further Reading

For more information about EF Core value converters and other advanced topics, refer to the following resources:

Feedback and Questions

We’d love to hear your feedback on this tutorial! If you have any questions or suggestions for improvement, please don’t hesitate to reach out. You can leave a comment below, or you can contact us through the following channels:

  1. Email: shady@shadynagy.com
  2. Twitter: @ShadyNagy_
  3. LinkedIn: Shady Nagy
  4. GitHub: ShadyNagy

We’ll do our best to address any questions or concerns you may have. We look forward to hearing from you and helping you make the most of EF Core value converters in your projects!


Tags

#microsoft#dotnet6#dotnet#dotnet core#ef core#ef#entity framework#entity framework core#C##csharp#api#api template#endpoints template#shady nagy api template#ShadyNagy.ApiTemplate#CleanArchitecture#Clean Architecture#value converters

Share


Previous Article
Resolving Git Index Error
Shady Nagy

Shady Nagy

Software Innovation Architect

Topics

AI
Angular
dotnet
GatsbyJS
Github
Linux
Oracle
MS SQL

Related Posts

Unraveling Performance Bottlenecks in .NET Applications A Deep Dive with Code Examples
Unraveling Performance Bottlenecks in .NET Applications A Deep Dive with Code Examples
December 31, 2023
1 min

Quick Links

Contact Us

Social Media