EF Core - Value Conversions based on a database column value
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?