EntityFrameworkCore 有没有办法创建 EnumToStringConverter 而不将枚举类型作为泛型传递?

Jun*_*ior 3 c# reflection entity valueconverter entity-framework-core

我正在尝试使用EntityFrameworkCoreORM 与我的数据库进行交互。默认情况下,EntityFrameworkCore似乎将枚举存储为 int 而不是字符串。

但是,我想将该值作为字符串存储在数据库中。我可以看到它EntityFrameworkCore带有一个名为EnumToStringConverter的转换器。

我正在尝试使用反射来设置模型构建器,因此我不必手动构建每个模型。

我遇到的问题是EnumToStringConverter接受必须是enum. 但是由于我在这里尝试使用反射,因此在创建转换器时无法传递枚举类型

这是我的代码到目前为止的样子

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

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

上述代码的唯一问题是EnumToStringConverter的构造方式。如果以某种方式我可以Type向 的构造函数提供 aEnumToStringConverter而不是将它作为可以解决问题的通用参数传递。

Iva*_*oev 5

预定义转换文档部分所述:

对于存在内置转换器的常见转换,无需明确指定转换器。相反,只需配置应使用的提供程序类型,EF 将自动使用适当的内置转换器。枚举到字符串的转换用作上面的示例,但如果配置了提供程序类型,EF 实际上会自动执行此操作:

接着是一个例子。

之后,您可以简单地使用:

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;
}
Run Code Online (Sandbox Code Playgroud)