【发布时间】:2018-06-15 17:26:18
【问题描述】:
我正在尝试使用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,而不是将其作为通用参数传递来解决问题。
【问题讨论】:
标签: c# reflection entity entity-framework-core valueconverter