1

I am using EF6 code first approach, wherein i have class with CreatedDate field, i have decorated it with [DefaultValue("getutcdate()")] and the Default binding has also been generated by EF, however, when i do not set any value for this field it sets as 0001-01-01 00:00:00.0000000, but since i have setuped the default value for this field, ain't it should set the current datetime, instead of this value.

Here's my class which has CreatedDate field:

public class User 
{
    [DefaultValue("getutcdate()")]
    public Datetime CreatedDate { get; set; }
}
Abbas
  • 4,948
  • 31
  • 95
  • 161
  • This isn't a duplicate, that question was how to apply default value, and mine was DefaultValue has been applied, but it doesn't sets current datetime as default. – Abbas Mar 06 '18 at 16:03
  • It *is* a duplicate, an exact one. `DefaultValue` specifies *values* not functions. The duplicate shows multiple ways that you can specify a function, either through a custom attribute or configuring the context – Panagiotis Kanavos Mar 06 '18 at 16:19
  • Check [EF6: Adding a Created Date/Time Column Automatically with Code First Migrations](https://andy.mehalick.com/2014/02/06/ef6-adding-a-created-datetime-column-automatically-with-code-first-migrations/) too. It shows how to specify the default function in the migration class – Panagiotis Kanavos Mar 06 '18 at 16:23
  • @Abbas Read all the answers, esp. [this one](https://stackoverflow.com/a/38102266/861716). Your problem is that the value is set by INSERT/UPDATE statements. That always overrides default constraints. – Gert Arnold Mar 06 '18 at 16:24
  • @PanagiotisKanavos i have implemented exact that solution only, as mentioned on that SO question, however, still it does not set the default value. – Abbas Mar 06 '18 at 16:51
  • Update the question then and show the migration code. Did you *run* the migration or just added the class? What is the schema of the generated table? – Panagiotis Kanavos Mar 06 '18 at 16:52
  • @Abbas besides, `public Datetime CreatedDate` *ALWAYS* has a value. It's a struct with a default value of `0001-01-01`. If you *don't* want to use it, you should add the `[DatabaseGenerated(DatabaseGeneratedOption.Computed)]` attribute. That's also shown in the linked answers – Panagiotis Kanavos Mar 06 '18 at 16:54
  • Thanks @PanagiotisKanavos, [DatabaseGenerated(DatabaseGeneratedOption.Computed)] fixed the issue, thanks a lot. – Abbas Mar 06 '18 at 17:23

0 Answers0