Home > database >  How to make a custom HasConversion method
How to make a custom HasConversion method

Time:09-22

im trying to make a custom EF HasConversion method, but I cant get it working. I dont't know what Im doing wrong.

I want to serialize object to Json String and deserialize Json String to Object.

This is my converter in DbContext thats working properly:

modelBuilder.Entity<Customer>(entity =>
        {
            entity.Property(k => k.Id).ValueGeneratedNever();
            entity.Property(e => e.ClientSettings)
            .HasConversion(
                v => JsonSerializer.Serialize(v, jsonSerializerOptions),
                v => JsonSerializer.Deserialize<CustomerClientSettings>(v, jsonSerializerOptions)
            );
        });

This is my custom converter that isn't working:

public static class ClientSettingsConverter
{
    public static EntityTypeBuilder<TEntity> MapClientSettings<TEntity>(this EntityTypeBuilder<TEntity> entity)
    where TEntity : class
    {
        
        entity.Property("ClientSettings")
        .HasConversion(
            v => JsonSerializer.Serialize(v, jsonSerializerOptions),
            v => JsonSerializer.Deserialize<TClientSettings>(v, jsonSerializerOptions)
        );

        return entity;
    }
}

The error I'm getting is at JsonSerializer.

Cannot convert lambda expression to type 'Type' because it is not a delegate type

I want to use it in my code like this so I don't need to write it each time again.

entity.Property(e => e.ClientSettings).MapClientSettings<CustomerClientSettings>() ;

Please can somebody help me how to solve this problem ? I'm really getting lost. Thank you.

CodePudding user response:

You can create CustomConverter using ValueConverter

public class CustomConverter<T> : ValueConverter<T, string> where T : class
{

    public CustomConverter() : base(
        v => JsonSerializer.Serialize(v, new JsonSerializerOptions { WriteIndented = true }),
        v => JsonSerializer.Deserialize<T>(v, new JsonSerializerOptions { WriteIndented = true }))
    {}
}

usage:

 entity.Property(e => e.ClientSettings)
            .HasConversion<CustomConverter<CustomerClientSettings>>();
  • Related