EF Core - Value Conversions based on a database column value

KKamal 1 Reputation point
2021-05-21T15:34:00.717+00:00

Hi All,

I need to encrypt some sensitive database columns while saving them to database and need to decrypt while reading them back from database. We are using EF core in our project. I plan to use EF Core - Value conversions as explained here (https://learn.microsoft.com/en-us/ef/core/modeling/value-conversions?tabs=fluent-api#encrypt-property-values).

Additionally we have the requirement that the above encryption/decryption is optional based on deployment model but our code base would be common for both the case. And due to some other use case as well, we plan to add a new column to each table "IsEncrypted" which would tell if a row is encrypted or not. Based on its value we would need to encrypt and decrypt the column values.

Example -

TableName - ContactInfo

Columns - Id, PhoneNumber, Address, IsEncrypted (The phone number column would need to encrypted/decrypted)

entity.Property(e => e.PhoneNumber)  
    .HasConversion(  
           val => Encrypt(val),  
           val => Decrypt(val));  

The above code does the encryption/decryption and works well. The challenge I am facing is how to do this based on "IsEncrypted" value.

Can someone please help me here?

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
779 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.