Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Store all enums as string global configuration #25929

Closed
matthiaslischka opened this issue Sep 8, 2021 · 3 comments
Closed

Store all enums as string global configuration #25929

matthiaslischka opened this issue Sep 8, 2021 · 3 comments

Comments

@matthiaslischka
Copy link
Contributor

I want to configure all enums to be stored as string instead of int just to be more readable in the DB.

I came up with this code to configure that globally for all enums and am wondering if there is a better way to do that or another best practice.

Also noticed that the string is nvarchar(max) - not sure if I should even care about that, but since I'm already here...

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    SetEnumToStringValueConverter(modelBuilder);
}

private void SetEnumToStringValueConverter(ModelBuilder modelBuilder)
{
    foreach (var property in modelBuilder.Model.GetEntityTypes().SelectMany(t => t.GetProperties()))
    {
        var enumType = GetEnumType(property.ClrType);
        if (enumType == null)
            continue;

        var type = typeof(EnumToStringConverter<>).MakeGenericType(enumType);

        var converter = Activator.CreateInstance(type, new ConverterMappingHints()) as ValueConverter;
        property.SetValueConverter(converter);
    }
}

private Type? GetEnumType(Type type)
{
    if (type.IsEnum) return type;

    var nullableUnderlyingType = Nullable.GetUnderlyingType(type);
    if (nullableUnderlyingType?.IsEnum ?? false) return nullableUnderlyingType;

    return null;
}

I did not find anything about global configuration in the official documentation. Did I just not find it or is it not there on purpose?
My reason for configuring it globally is because I want behavior like that to be at least consistent throughout my application.

BR Matthias

@ajcvickers
Copy link
Member

@ajcvickers ajcvickers reopened this Oct 16, 2022
@ajcvickers ajcvickers closed this as not planned Won't fix, can't repro, duplicate, stale Oct 16, 2022
@tscheler
Copy link

tscheler commented Sep 8, 2023

Using EFCore 7.0.10 here, this works with MariaDb:

 configurationBuilder.Properties<Enum>().HaveConversion<string>();

Any objections to this approach?

@roji
Copy link
Member

roji commented Sep 8, 2023

@tscheler that's indeed the recommended way to do this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants