Entity Framework 6 Code First default datetime value on insert

23,118

Solution 1

Try this:

[DatabaseGenerated(DatabaseGeneratedOption.Identity), DataMember]
public DateTime?            Registered          { get; private set; }

The question mark makes the property nullable

Solution 2

There is no default DateTime. Only a min value.

You could potentially just set the datetime on that entity before calling dbContext.SaveChanges.

See this for a solution.

Solution 3

This technique behaves like a readonly field that is persisted to the database. Once the value is set it cannot (easily) be changed by using code. (Of course, you change the setter to public or internal if needed.)

When you create a new instance of a class that uses this code Registered will not initially be set. The first time the value of Registered is requested it will see that it has not been assigned one and then default to DateTime.Now. You can change this to DateTime.UTCNow if needed.

When fetching one or more entities from the database, Entity Framework will set the value of Registered, including private setters like this.

private DateTime? registered;
[Required]
public DateTime Registered
{
    get
    {
        if (registered == null)
        {
            registered = DateTime.Now;
        }
        return registered.Value;
    }
    private set { registered = value; }
}
Share:
23,118
Atrotygma
Author by

Atrotygma

Updated on July 09, 2022

Comments

  • Atrotygma
    Atrotygma almost 2 years

    When I'm saving changes to the database, I'm running into the following exception:

    Cannot insert the value NULL into column 'Registered', table
    'EIT.Enterprise.KMS.dbo.LicenseEntry'; column does not allow nulls.
    INSERT fails. The statement has been terminated.
    

    The related code first model property looks like this:

    [DatabaseGenerated(DatabaseGeneratedOption.Identity), DataMember]
    public DateTime         Registered          { get; private set; }
    

    ... and here's why I'm confused: As far as I know, by providing the annotation [DatabaseGenerated(DatabaseGeneratedOption.Identity) I'm ordering Entity Framework to auto-generate the field (in this case: Only once at creation time.)

    So I'm expecting to have a non-nullable (required) field, without the possibility to alter the field manually where EF is taking care of.

    What am I doing wrong?


    Notes:

    1. I don't want to use Fluent-API, as I want to use POCOs.
    2. The property defaultValueSql is also not an option, because I need to rely database independed for this project (e.g. for GETDATE()).
    3. I'm using Entity Framework 6 alpha 3, Code First.