What I am trying to achieve
I would like to create a ValueConverter for my application so that I can encrypt string values in my database. I know this exists, I would prefer to do it myself.
The issue I am running into
I am getting a System.NullReferenceException: Object reference not set to an instance of an object. error when I try to call my context. I have tried removing properties, rewriting constructors, changed up static methods, with no success.
Code
Value Converter
public class AesGcmConverter : ValueConverter<string, string>
{
public AesGcmConverter(ConverterMappingHints mappingHints = default) : base(EncryptExpr, DecryptExpr, mappingHints)
{
}
static Expression<Func<string, string>> DecryptExpr = x => new string(x.Reverse().ToArray());
static Expression<Func<string, string>> EncryptExpr = x => new string(x.Reverse().ToArray());
}
EF
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
foreach (var property in entityType.GetProperties())
{
var attributes = property.PropertyInfo.GetCustomAttributes(typeof(EncryptedAttribute), false);
if (attributes.Any())
{
property.SetValueConverter(new AesGcmConverter());
}
}
}
}