Course contentsShow
← C#
Lesson 1133 of 1,90810. Entity Framework Core ModelingFree lesson

Custom Value Providers

Handle encryption and decryption automatically at the model-database boundary.

Mastering Custom Value Providers in EF Core

In this lesson, you will learn how to implement Custom Value Providers to automatically encrypt and decrypt sensitive data as it travels between your C# objects and your database.

The Problem: Sensitive Data at Rest

Often, you need to store sensitive information—like a user's Social Security Number or an API secret—in a database, but you don't want that data stored in plain text. Manually encrypting properties every time you save a record and decrypting them every time you read one is error-prone and clutters your business logic.

The Solution: Value Converters

EF Core provides ValueConverter, a mechanism that sits at the model-database boundary. It acts as a transparent bridge: when you save an entity, EF Core intercepts the property value, runs your encryption logic, and sends the ciphertext to the database. When you query the data, it intercepts the ciphertext, runs your decryption logic, and populates your entity with the original, plain-text value.

Here is a simplified look at how you would configure this in your DbContext:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    // Define the converter
    var encryptionConverter = new ValueConverter<string, string>(
        v => Encrypt(v), // Logic to run before saving to DB
        v => Decrypt(v)  // Logic to run after loading from DB
    );

    // Apply the converter to a specific entity property
    modelBuilder.Entity<User>()
        .Property(u => u.NationalId)
        .HasConversion(encryptionConverter);
}

Why this works

By isolating the conversion logic, your domain entities remain clean and ignorant of the security layer. Your application code continues to interact with the NationalId as a standard string, while the ValueConverter ensures that sensitive data is never stored in plain text on the disk. This approach is superior to manual handling because it is centralized, consistent, and invisible to your service-layer logic.

Key Takeaway: Custom Value Providers allow you to centralize sensitive data transformations within your EF Core configuration, ensuring that encryption and decryption happen automatically at the database boundary without polluting your entity logic.