【发布时间】:2018-03-18 00:56:34
【问题描述】:
我发现的所有关于声明默认值的方法都是在 Sql 脚本中生成默认值,而不是在迁移代码中。
我最喜欢使用属性:https://stackoverflow.com/a/34894274/132942
[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://stackoverflow.com/a/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()")内CreateTable调用)。你确定你的自定义迁移代码生成器被调用了吗?例如Configuration类中的行将其设置为CodeGenerator?
标签: entity-framework entity-framework-6 ef-code-first default-value entity-framework-migrations