更改属性默认值



在EntityFramework 6中,我可以做以下事情来更改特定数据类型的默认值:

protected override void OnModelCreating(
DbModelBuilder mb
) {
mb
.Properties<DateTime>()
.Configure(config => 
config
.HasColumnType("datetime2")
.HasPrecision(7)
);

这节省了为DB中的每个DateTime属性指定这些详细信息。

是否有一个等效的方法来改变EF Core的属性默认值?EF CoreModelBuilder类型中没有Properties成员

我已经为此创建了一个扩展方法

public static class ModelBuilderExtensions
{
public static void Properties<TPropertyType>(
this ModelBuilder modelBuilder,
Action<IMutableProperty> configureAction
)
{
modelBuilder
.Model
.GetEntityTypes()
.SelectMany(entityType => entityType.GetProperties())
.Where(entityProperty => typeof(TPropertyType) == entityProperty.ClrType)
.ToList()
.ForEach(configureAction);
}
}

然后我可以这样做:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Properties<DateTimeOffset>(
property =>
{
if (property.Name == nameof(Entity.CreatedAtUtc))
{
property.SetDefaultValueSql("CURRENT_TIMESTAMP AT TIME ZONE 'UTC'");
}
}
);
}

最新更新