Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute

后端 未结 21 1402
终归单人心
终归单人心 2020-11-29 22:53

Does any one know how I can specify the Default value for a DateTime property using the System.ComponentModel DefaultValue Attribute?

for example I try this:

21条回答
  •  Happy的楠姐
    2020-11-29 23:21

    There's no reason I can come up with that it shouldn't be possible to do through an attribute. It might be in Microsoft's backlog. Who knows.

    The best solution I have found is to use the defaultValueSql parameter in the code first migration.

    CreateTable(
        "dbo.SomeTable",
        c => new
            {
                TheDateField = c.DateTime(defaultValueSql: "GETDATE()")
            });
    

    I don't like the often reference solution of setting it in the entity class constructor because if anything other than Entity Framework sticks a record in that table, the date field won't get a default value. And the idea of using a trigger to handle that case just seems wrong to me.

提交回复
热议问题