gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:55:38 25 4
gpt4 key购买 nike

我正在尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com