Entity Framework Core DateTime field getting updated to 1/1/0001

asp.net-core c# dbcontext entity-framework-core sql-server


I am facing one issue related to Entity Framework Core. I have DateTime field in table as shown below.

Table Column - datetime2 (7) & Nullable - False

This column is mapped on Entity in asp.net core code to class property as shown below.

public DateTime dateCreated { get; set; }

Whenever I am updating(Adding has no issue) the record, the table field is getting set to 1/1/0001 12:00AM. Logically datecreated field should not get updated.

I tried changing the ModalSnapshot but no luck

   **.ValueGeneratedNever();**  // Added this line  but there is not effect.

Could anyone please guild me what is the issue.

Thanks in advance.

4/10/2020 4:55:21 PM

Popular Answer

What I found is that we have to maintain the value across edit's and update's.

When we retrieve the record from database for edit, we have to assign dateCreated value to entity field. Same for update we have to pass same value that we retrieved while getting the record.

I was not doing this because I was assuming Entity Framework will handle it. As the fields is not null and already there is value in the field(value that is added while adding the record). I was expecting it will not touch the value.

This behavior is because of not null column in database, entity framework assigns default 1/1/0001 12:00AM if we are not explicitly specifying.

//Added this line in get and update method.
//Date created 
Entity               Record from db
entity.dateCreated = entity.dateCreated;


4/10/2020 7:02:27 PM

Related Questions


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