Entity Framework 6 Code First default datetime value on insert

.net c# entity-framework sql

Question

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.
1
6
6/11/2013 3:34:07 PM

Accepted Answer

Try this:

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

The question mark makes the property nullable

3
6/11/2013 3:42:24 PM

Popular Answer

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; }
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow