Search code examples
c#reflectionentityentity-framework-corevalueconverter

EntityFrameworkCore is there a way to create EnumToStringConverter without passing the enum type as generic?


I am trying to use EntityFrameworkCore ORM to interact with my databases. By default, EntityFrameworkCore seems to store enum as int instead of string.

However, I would like to store the value in the database as a string. I can see that EntityFrameworkCore ships with a converter called EnumToStringConverter.

I am trying to use reflection to setup the model builder so I don't have to manually build each model.

The issue that I am running into is that EnumToStringConverter accepts a generic type which must be an enum. But since I am trying to use reflection here I am unable to pass the enum type when creating the converter

Here is what my code look like so far

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

    // Get all DbSet<> properties that are defined in the DbContext
    var modelTypes = typeof(DataContext).GetProperties()
                                        .Where(x => x.PropertyType.IsGenericType && x.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>))
                                        .Select(x => x.PropertyType.GetGenericArguments().First())
                                        .ToList();

    foreach (Type modelType in modelTypes)
    {
        var properties = modelType.GetProperties();

        foreach (var property in properties)
        {
            if (IsPrimaryKey(property))
            {
                // At this point we know that the property is a primary key
                modelBuilder.Entity(modelType)
                            .Property(property.Name)
                            .UseSqlServerIdentityColumn()
                            .Metadata.BeforeSaveBehavior = PropertySaveBehavior.Ignore;

                continue;
            }

            if (property.PropertyType.IsEnum)
            {
                // At this point we know that the property is an enum.
                // Add the EnumToStringConverter converter to the property so that
                // the value is stored in the database as a string instead of number 
                var converter = new EnumToStringConverter(); // if somehow I can change this code to something like var `new EnumToStringConverter(property.PropertyType);` the code would work

                modelBuilder.Entity(modelType)
                            .Property(property.Name)
                            .HasConversion(converter);

                continue;
            }

        }
    }
}

The only issue with the above code is how EnumToStringConverter is constructed. If somehow I can provide a Type to the constructor of the EnumToStringConverter instead of passing it as a generic argument that would solve the problem.


Solution

  • As explained in the Pre-defined conversions documentation section:

    For common conversions for which a built-in converter exists there is no need to specify the converter explicitly. Instead, just configure which provider type should be used and EF will automatically use the appropriate build-in converter. Enum to string conversions are used as an example above, but EF will actually do this automatically if the provider type is configured:

    followed by an example.

    Following that, you could simply use:

    if (property.PropertyType.IsEnum)
    {
        // At this point we know that the property is an enum.
        // Add the EnumToStringConverter converter to the property so that
        // the value is stored in the database as a string instead of number 
        modelBuilder.Entity(modelType)
            .Property(property.Name)
            .HasConversion<string>(); // <--
    
        continue;
    }