Firstly, there are a lot of answers in this StackOverflow question that are of a similar ilk which helped me get very close, but none quite work in my situation.
I have a model class:
public class TestModel
{
[Key]
public int TestModelId { get; set; }
public DateTime CreatedOn { get; set; }
}
And this is added to a DbContext file like so:
public virtual DbSet<TestModel> TestModels { get; set; }
So on add-migration this produces:
...
migrationBuilder.CreateTable(
name: "TestModels",
columns: table => new
{
TestModelId = table.Column<int>(nullable:false)
.Annotation("SqlServer:Identity", "1, 1"),
CreatedOn = table.Column<DateTime>(nullable:false)
},
...
Now I'm trying to get a one-stop place to make sure the CreatedOn column builder has the default GETDATE() in there:
CreatedOn = table.Column<DateTime>(nullable:false, defaultValueSql: "GETDATE()")
which I know works perfectly when translating it to the SQL Server side, but I've tried several data annotation and constructor versions as per the linked question to no avail e.g. the attribute
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
does nothing and I don't want to have to manually add the defaultValueSql part to the migration file every time I create one / it.
So where can I do this in the models?