我发现的所有有关声明默认值的方法都是在 SQL 脚本中生成默认值,而不是在迁移代码中生成。
我最喜欢的方法是使用属性:https://dev59.com/nWIk5IYBdhLWcg3wI7AF#34894274。
在上下文的"OnModelCreating"中添加
我最喜欢的方法是使用属性:https://dev59.com/nWIk5IYBdhLWcg3wI7AF#34894274。
[SqlDefaultValue(DefaultValue = "getutcdate()")]
public DateTime CreatedDateUtc { get; set; }
属性定义
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class SqlDefaultValueAttribute : Attribute
{
public string DefaultValue { get; set; }
}
在上下文的"OnModelCreating"中添加
modelBuilder.Conventions.Add( new AttributeToColumnAnnotationConvention<SqlDefaultValueAttribute, string>("SqlDefaultValue", (p, attributes) => attributes.Single().DefaultValue));
然后是定制SqlGenerator。但我不喜欢这个方式,因为我无法确定生成的迁移是否符合我的期望。
为了解决这个问题,我修改了MigrationCodeGenerator如下:https://dev59.com/ZWoy5IYBdhLWcg3wYc8l#21024108
在自定义的MigrationCodeGenerator中
public class ExtendedMigrationCodeGenerator : MigrationCodeGenerator
{
public override ScaffoldedMigration Generate(string migrationId, IEnumerable<MigrationOperation> operations, string sourceModel, string targetModel, string @namespace, string className)
{
foreach (MigrationOperation operation in operations)
{
if (operation is CreateTableOperation)
{
foreach (var column in ((CreateTableOperation)operation).Columns)
{
System.Data.Entity.Infrastructure.Annotations.AnnotationValues values;
if (column.Annotations.TryGetValue("SqlDefaultValue", out values))
{
column.DefaultValueSql = (string)values.NewValue;
}
}
}
else if (operation is AddColumnOperation)
{
ColumnModel column = ((AddColumnOperation)operation).Column;
System.Data.Entity.Infrastructure.Annotations.AnnotationValues values;
if (column.Annotations.TryGetValue("SqlDefaultValue", out values))
{
column.DefaultValueSql = (string)values.NewValue;
}
}
}
CSharpMigrationCodeGenerator generator = new CSharpMigrationCodeGenerator();
return generator.Generate(migrationId, operations, sourceModel, targetModel, @namespace, className);
}
}
但是在使用ScaffoldedMigration方法时,我无法获取我的自定义注释SqlDefaultValue或任何其他注释。
是否有可能获取这个注释?
CreatedDateUtc = c.DateTime(nullable: false, defaultValueSql: "getutcdate()")
)。你确定你的自定义迁移代码生成器被调用了吗?例如,在Configuration
类中设置它为CodeGenerator
的那一行? - Ivan Stoev