Tachyon
Tachyon

Reputation: 2411

ValueConverter Entity Framework Core

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());
            }
        }
    }
}

Upvotes: 1

Views: 535

Answers (1)

Omda
Omda

Reputation: 11

On which line do you catch exception? hint : perhaps you have null string value in database, then calling x.Reverse() would throw NullReferenceObject exception when x is null

Upvotes: 1

Related Questions