EF 7數據庫日期時間生成的值


我有這個模型

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

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

我試圖讓數據庫生成的值CreatedAtLastEditedAt所以在我OnModelCreating我的方法DbContext我用

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

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

在嘗試插入時,我在SaveChanges()得到一個內部異常

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

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

這是否意味著我必須手動為這兩列賦值?

通過使LastEditedAt空來修復

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

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

並將SQL默認值設置為CreatedAt

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

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

一般承認的答案

您可以將DateTime設置為可空: DateTime?





許可下: CC-BY-SA
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因