c# - EntityFrameworkCore 有没有一种方法可以创建 EnumToStringConverter 而无需将枚举类型作为通用类型传递?

标签 c# reflection entity entity-framework-core valueconverter

我正在尝试使用 EntityFrameworkCore ORM 与我的数据库进行交互。默认情况下,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;
            }

        }
    }
}

上面代码的唯一问题是如何EnumToStringConverter被构造。如果我能以某种方式向 EnumToStringConverter 的构造函数提供 Type,而不是将其作为通用参数传递,这样就可以解决问题。

最佳答案

Pre-defined conversions 中所述文档部分:

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:

后面是一个例子。

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

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

关于c# - EntityFrameworkCore 有没有一种方法可以创建 EnumToStringConverter 而无需将枚举类型作为通用类型传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50880217/

相关文章:

c# - 选择合适的微 Controller 来连接 RFID 和用 C# 开发的软件

c# - Progress<T> 与 Action<T> 有何不同? (C#)

java - 又是: How to solve 'Repeated column in mapping for collection' ?

c# - 使用值列表循环遍历 C# 中的字典

c# - 静态方法和访问变量的能力

java.beans.Introspector getBeanInfo 不获取任何超接口(interface)的属性

c# - 使用 InvokeMember 检索静态属性值

java - 如何使用Java Reflection获取 "method"的实际执行时间?

java - 实体类方法中的数学逻辑问题

c# - 简单的 LINQ 计数,或者我认为