All the approaches I've found about declaring default values, generates the default value in the Sql script, not in the migration code.
My favorite is using attributes: https://stackoverflow.com/a/34894274/132942
[SqlDefaultValue(DefaultValue = "getutcdate()")]
public DateTime CreatedDateUtc { get; set; }
Attribute definition
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class SqlDefaultValueAttribute : Attribute
{
public string DefaultValue { get; set; }
}
In the "OnModelCreating" of the context adding
modelBuilder.Conventions.Add( new AttributeToColumnAnnotationConvention<SqlDefaultValueAttribute, string>("SqlDefaultValue", (p, attributes) => attributes.Single().DefaultValue));
And then customizing the SqlGenerator. But I don't like this because I don't see when generating the migration if everything it's as I wanted.
To do so, I modified the MigrationCodeGenerator like this: https://stackoverflow.com/a/21024108
In the custom 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);
}
}
But in the method ScaffoldedMigration I cannot get my custom annotation SqlDefaultValue or any other annotation.
Is it possible to get this annotation?