Mickael Caruso
Mickael Caruso

Reputation: 9491

Entity Framework SaveChanges() does not insert DateTime? when It's Specified

I have a class MyEntity with a DateTime? CreatedDate { get; set; } property.

So I create my Entity:

MyEntity e = new MyEntity { Id = 0, ..., CreatedDate = DateTime.Now };

db.MyEntities.Add(e);
db.SaveChanges();

I look in the database and the CreatedDate field is null. Why? I specified it right before adding to the context!

In tried others' suggestions of setting CreatedDate = DateTime.Now as DateTime?; or even CreatedDate = DateTime.Now as Nullable<DateTime>; Same result - inserting is null.

Upvotes: 0

Views: 3206

Answers (4)

acelot
acelot

Reputation: 762

Set a breakpoint after entity instance creation and check properties. Is CreatedDate set properly?

Upvotes: 0

Mickael Caruso
Mickael Caruso

Reputation: 9491

I didn't tell you guys earlier but I had decorated DateTime? CreatedDate with [DatabaseGenerated(DatabaseGeneratedOption.Computed)] which I didn't think affected create or update.

If I had this attribute, any in-C# effort to set CreateDate will result in null. To fix the null problem, I had to go to Configuration.cs and write c => c.DateTime(defaultSqlValue: "GETDATE()") to the corresponding column definition. Took care of the problem.

Alternatively, I could just get rid of the annotation and not touch the Configuration.cs file.

Upvotes: 0

uk2k05
uk2k05

Reputation: 388

Could the issue be that in the first line of code you are declaring a new class of type Entity instead of MyEntity?

try..

MyEntity e = new MyEntity { Id = 0, ..., CreatedDate = DateTime.Now };

db.MyEntities.Add(e);
db.SaveChanges();

Upvotes: 1

Shahzad Khan
Shahzad Khan

Reputation: 530

CreatedDate = DateTime.Now.Date

set the createddate as date

Upvotes: 0

Related Questions