Setting the default value of a DateTime Property

S A 81 Reputation points
2022-03-17T10:33:28.963+00:00

I’m using the below code to set default date to the field DateCreated.

public DateTime DateCreated
{
get
{
return this.dateCreated.HasValue
? this.dateCreated.Value
: DateTime.Now;
}

set { this.dateCreated = value; }
}

private DateTime? dateCreated = null;

After executing the command „update-database“ the entity framework gives such error:
InvalidOperationException: Nullable object must have a value.
Where is the problem?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,400 questions
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 27,696 Reputation points
    2022-03-17T13:42:48.247+00:00

    I would like to solve the problem in the level of Model properties.

    I recommend following standards patterns and practices and creating a table constraint as illustrated in the reference documentation.

    However, if you really need to do this in C# then set the value in the class constructor.

    public class DefaultDemo  
    {  
        public DefaultDemo()  
        {  
            DateCreated = DateTime.Now;  
        }  
        public DateTime DateCreated { get; set; }  
    }  
    

    Constructors (C# programming guide)

    Or assign the value.

    public DateTime? DateCreated { get; set; } = DateTime.Now;  
    

    If your logic has a CreateDate to assign you can simply assign the date to override the default set in code.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. AgaveJoe 27,696 Reputation points
    2022-03-17T11:43:28.307+00:00

    Please read the official documentation which covers configuring default values in EF Core.

    https://learn.microsoft.com/en-us/ef/core/modeling/generated-properties?tabs=data-annotations#datetime-value-generation