我有这个模型
public class Comment
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CommentId { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime LastEditedAt { get; set; }
}
我试图让db生成CreatedAt
和LastEditedAt
的值,所以在我使用的OnModelCreating
DbContext
方法中
modelBuilder.Entity<Comment>(c =>
{
c.Property(p => p.CreatedAt).ValueGeneratedOnAdd();
c.Property(p => p.LastEditedAt).ValueGeneratedOnAddOrUpdate();
});
尝试插入时,我会在SaveChanges()
说
{"Cannot insert the value NULL into column 'CreatedAt', table 'WX.dbo.Comment'; column does not allow nulls. INSERT fails."}
这是否意味着我必须手动为这两列分配值?
通过使LastEditedAt
可以为空而修复
public DateTime CreatedAt { get; set; }
public DateTime? LastEditedAt { get; set; }
并将SQL默认值设置为CreatedAt
modelBuilder.Entity<Comment>(c =>
{
c.Property(p => p.CreatedAt).HasDefaultValueSql("GETUTCDATE()");
c.Property(p => p.LastEditedAt).ValueGeneratedOnAddOrUpdate();
});