Reputation: 9491
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
Reputation: 762
Set a breakpoint after entity instance creation and check properties. Is CreatedDate set properly?
Upvotes: 0
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
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