DEV Community

Cover image for EF Core string conversions
Karen Payne
Karen Payne

Posted on

EF Core string conversions

EF Core provides methods to transform one type into another. Most common use is with enumerations (see using Enum with EF Core) while many other transformations are possible.

In this article a string property Password is encrypted when saving to a database table and decrypted when reading from the database table.

Microsoft simple starter code sample for HasConversion which in this case takes a string and reverses the string and stores in the table then read back reverses the value back to what was entered.

Original conversion

Which allows a developer to work from a simple example to implement their own logic while in this project a NuGet package is used as per below.

modelBuilder.Entity<User>().Property(e => e.Password).HasConversion(
    v => new string(v.Reverse().ToArray()),
    v => new string(v.Reverse().ToArray()));
Enter fullscreen mode Exit fullscreen mode

Current conversion

The conversion here is done with NuGet package Inferno crypto library, Once configured as shown below the conversion is seamless.

OnModelCreating code

inferno crypt library

While many developers are aware enough not to roll their own crypto, they either pick the wrong approach, screw up the implementation, or both. Many of these libraries focus on providing as many crypto primitives as possible, which is a huge disservice.

I highly recommend taking time to read the docs.

Note
Before running this project the database must be created with the script under the folder Scripts

Source code

Clone the following GitHub repository

See also

Microsoft: Pre-defined conversions

Summary

What has been presented is not true encryption but a lesson in using transformations with EF Core.

Top comments (0)