Setting the default value of a DateTime Property

S A 81 Reputation points

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

public DateTime DateCreated
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?

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

Accepted answer
  1. AgaveJoe 26,161 Reputation points

    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 26,161 Reputation points

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