static void ApplyGenericConverter(ModelBuilder modelBuilder, Type commonType, Type converterGenericType, int? maxLength = null)
{
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
var properties = entityType.ClrType.GetProperties()
.Where(p => p.PropertyType.IsAssignableTo(commonType));
foreach (var property in properties)
{
var converterType = converterGenericType.MakeGenericType(property.PropertyType.GenericTypeArguments[0]);
var converter = Activator.CreateInstance(converterType);
if (converter is null)
{
throw new Exception("Error creating the dynamic converter object: " + entityType.ClrType.ToString() + " Property: " + property.ToString());
}
var builder = modelBuilder.Entity(entityType.Name).Property(property.Name)
.HasConversion((ValueConverter)converter);
if (maxLength is int ml) builder = builder.HasMaxLength(ml);
}
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
ApplyGenericConverter(modelBuilder, typeof(IEntityId), typeof(EntityIdValueConverter<>), maxLength: 26 + 1 + 3);
ApplyGenericConverter(modelBuilder, typeof(IJsonBox), typeof(JsonBoxValueConverter<>));
}