I'm trying to generate automatically a default value for metadata columns in my code first database. It seems like code first migration fluent api does not handle HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed)
Every table in my DB has a "CREATION_DATE" column using default value "getdate()". In my EntityTypeConfiguration i try to use:
Property(p => p.CREATION_DATE).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);
This is generated for the migration:
CREATION_DATE = c.DateTime(nullable: false)
I can manually add defaultValueSql: "getdate()", but I don't want to do this every migration. I did write a SqlServerMigrationSqlGenerator for this, but it just does not seem to generate the default value.
internal sealed class Configuration : DbMigrationsConfiguration<TheModel>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
SetSqlGenerator(SqlProviderServices.ProviderInvariantName, new CustomMigrationSqlGenerator());
}
and in the CustomMigrationSqlGenerator class
protected override void Generate(CreateTableOperation createTableOperation)
{
SetDefaultDate(createTableOperation.Columns);
base.Generate(createTableOperation);
}
The default value is not generated with or without the CustomMigrationSqlGenerator.
Am I missing something? I read on forums that it was an issue at some point, but the posts date back from 2010-2012.
*Edit
Content of SetDefaultDate
private static void SetDefaultDate(IEnumerable<ColumnModel> columns)
{
foreach (var item in columns)
{
SetDefaultDate(item);
}
}
private static void SetDefaultDate(ColumnModel column)
{
if (column.Type.Equals(System.Data.Entity.Core.Metadata.Edm.PrimitiveTypeKind.DateTime))
{
column.DefaultValueSql = "getdate()";
}
}