在单个语句中为多个列设置默认值
Set default value for multiple columns in a single statement
我使用的是 EF Core Code-First,需要为多列设置默认值。
我知道这是为一列设置默认值的语句
modelBuilder.Entity<Registration>()
.Property(b => b.AdminFee)
.HasDefaultValue(25);
我有 10 个具有不同默认值的字段,想看看是否有一种简短的方法可以一次性设置所有默认值,而不是重复上述代码 10 次。
您可以使用元数据API来实现它。例如:
var myProps = new Dictionary<string, object>()
{
{ nameof(Registration.AdminFee), 25 },
{ nameof(Registration.AnotherProp1), 35 },
{ nameof(Registration.AnotherProp2), 18 },
{ ... }
};
foreach (var matchingProp in modelBuilder.Entity<Registration>()
.Metadata
.GetProperties()
.Where(x => myProps.ContainsKey(x.Name)))
{
matchingProp.Relational().DefaultValue = myProps[matchingProp.Name];
}
我使用的是 EF Core Code-First,需要为多列设置默认值。
我知道这是为一列设置默认值的语句
modelBuilder.Entity<Registration>()
.Property(b => b.AdminFee)
.HasDefaultValue(25);
我有 10 个具有不同默认值的字段,想看看是否有一种简短的方法可以一次性设置所有默认值,而不是重复上述代码 10 次。
您可以使用元数据API来实现它。例如:
var myProps = new Dictionary<string, object>()
{
{ nameof(Registration.AdminFee), 25 },
{ nameof(Registration.AnotherProp1), 35 },
{ nameof(Registration.AnotherProp2), 18 },
{ ... }
};
foreach (var matchingProp in modelBuilder.Entity<Registration>()
.Metadata
.GetProperties()
.Where(x => myProps.ContainsKey(x.Name)))
{
matchingProp.Relational().DefaultValue = myProps[matchingProp.Name];
}