EF 7 Database datetime generated value

entity-framework entity-framework-core

Question

I have this model

 public class Comment
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int CommentId { get; set; }

        public DateTime CreatedAt { get; set; }
        public DateTime LastEditedAt { get; set; }
    }

I'm trying to let the db generate the value of CreatedAt and LastEditedAt so in my OnModelCreating method of my DbContext I used

modelBuilder.Entity<Comment>(c =>
            {
                c.Property(p => p.CreatedAt).ValueGeneratedOnAdd();
                c.Property(p => p.LastEditedAt).ValueGeneratedOnAddOrUpdate();
            });

When trying to insert I get an inner exception in SaveChanges() saying

{"Cannot insert the value NULL into column 'CreatedAt', table 'WX.dbo.Comment'; column does not allow nulls. INSERT fails."}

Does that mean that I have to assign values to those two columns manually?

Fixed by making LastEditedAt nullable

 public DateTime  CreatedAt { get; set; }
 public DateTime? LastEditedAt { get; set; }

and setting an SQL default value to CreatedAt

  modelBuilder.Entity<Comment>(c =>
            {
                c.Property(p => p.CreatedAt).HasDefaultValueSql("GETUTCDATE()");
                c.Property(p => p.LastEditedAt).ValueGeneratedOnAddOrUpdate();
            });

Accepted Answer

You may set DateTime to nullable : DateTime?.



Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why