EF 7 Database datetime generated value
<p>I have this model</p>

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

        public DateTime CreatedAt { get; set; }
        public DateTime LastEditedAt { get; set; }
    }
</code></pre>

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

<pre><code>modelBuilder.Entity&lt;Comment&gt;(c =&gt;
            {
                c.Property(p =&gt; p.CreatedAt).ValueGeneratedOnAdd();
                c.Property(p =&gt; p.LastEditedAt).ValueGeneratedOnAddOrUpdate();
            });
</code></pre>

<p>When trying to insert I get an inner exception in <code>SaveChanges()</code> saying</p>

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

<p>Does that mean that I have to assign values to those two columns manually?</p>

<p>Fixed by making <code>LastEditedAt</code> nullable</p>

<pre><code> public DateTime  CreatedAt { get; set; }
 public DateTime? LastEditedAt { get; set; }
</code></pre>

<p>and setting an SQL default value to <code>CreatedAt</code></p>

<pre><code>  modelBuilder.Entity&lt;Comment&gt;(c =&gt;
            {
                c.Property(p =&gt; p.CreatedAt).HasDefaultValueSql("GETUTCDATE()");
                c.Property(p =&gt; p.LastEditedAt).ValueGeneratedOnAddOrUpdate();
            });
</code></pre>