Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 6 Code First default datetime value on insert

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.
like image 524
Atrotygma Avatar asked Jun 11 '13 15:06

Atrotygma


2 Answers

Try this:

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

The question mark makes the property nullable

like image 185
Sparky Avatar answered Oct 24 '22 05:10

Sparky


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.

like image 34
marcellscarlett Avatar answered Oct 24 '22 05:10

marcellscarlett