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();
});