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

后端 未结 21 1441
终归单人心
终归单人心 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条回答
  •  孤街浪徒
    2020-11-29 23:06

    I think you can do this using StoreGeneratedPattern = Identity (set in the model designer properties window).

    I wouldn't have guessed that would be how to do it, but while trying to figure it out I noticed that some of my date columns were already defaulting to CURRENT_TIMESTAMP() and some weren't. Checking the model, I see that the only difference between the two columns besides the name is that the one getting the default value has StoreGeneratedPattern set to Identity.

    I wouldn't have expected that to be the way, but reading the description, it sort of makes sense:

    Determines if the corresponding column in the database will be auto-generated during insert and update operations.

    Also, while this does make the database column have a default value of "now", I guess it does not actually set the property to be DateTime.Now in the POCO. This hasn't been an issue for me as I have a customized .tt file that already sets all of my date columns to DateTime.Now automatically (it's actually not hard to modify the .tt file yourself, especially if you have ReSharper and get a syntax highlighting plugin. (Newer versions of VS may already syntax highlight .tt files, not sure.))

    The issue for me was: how do I get the database column to have a default so that existing queries that omit that column will still work? And the above setting worked for that.

    I haven't tested it yet but it's also possible that setting this will interfere with setting your own explicit value. (I only stumbled upon this in the first place because EF6 Database First wrote the model for me this way.)

提交回复
热议问题