我们的目标
为了能够使用一个工具来自动从我们的数据库(MySQL
)中生成所有模型,并Null Safety
启用(Nullable
参考类型),这让我们可以修改一些属性的类型和值,而不会失去自动生成的所有优势。数据库字段不能更改。
我们现在的情况
我们正在使用 **Entity Framework scaffold
命令** 来生成我们的数据库模型。
我们正在使用HbsCSharpEntityTypeGenerator
从Handlebars库扩展的自定义类来修改属性的类型(我们使用它是因为我们只需要修改来自特定实体的属性),然后OnModelCreatingPartial(ModelBuilder modelBuilder)
在读取/保存到 DB 时使用它来转换值,一个例子:
public partial class ContextX
{
partial void OnModelCreatingPartial(ModelBuilder modelBuilder)
{
modelBuilder.Entity<EntityX>()
.Property(x => x.PropertyX)
.HasConversion(
// In our model this property is an int? but the DB doesn't allow nulls,
// in case of NULL we save 0 into the DB
x => x == null ? 0 : x,
// The DB field is int (using 0 as NULL), in case of 0 we set NULL in our model
x => x == 0 ? null : x);
}
}
问题
如此处所示,Entity Framework's
当类型为int
和时,不会调用属性转换器int?
,这意味着ValueConverter<int, string>
每次我们需要读取/保存到数据库时都会调用 a ,但不会调用 a ValueConverter<int?, int>
。
我们使用这种方法的主要原因是在我们的模型中使用 Nullable 类型和正确的值而不是错误的占位符(空字符串、零、错误的默认日期等),任何符合上述要求的解决方案都会很好。
先感谢您。