无法将值 NULL 插入列 'created_date'、table 'WebApp.dbo.Inventories';

Cannot insert the value NULL into column 'created_date', table 'WebApp.dbo.Inventories';

我创建了一个模型 BaseModel 来将这两个属性 date_createddate_modified 继承到我数据库中的所有模型,以便在创建记录和删除记​​录时保留记录已修改。

我为这些属性添加了?运算符来接受空值如下图:

基本型号:

namespace API.Models
{
    public class BaseModel
    {
        public BaseModel()
        {
            created_date = DateTime.Now;
        }

        public DateTime? created_date { get; set; }
        public DateTime? modified_date { get; set; }
    }
}

库存 table:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.AspNetCore.Mvc;

namespace API.Models
{
    public class Inventory : BaseModel
    {
        [Key]
        public int inventory_id { get; set; }
        [Required(ErrorMessage = "El campo {0} es obligatorio"), StringLength(10, ErrorMessage = "{0} la longitud debe estar entre {2} y {1}.", MinimumLength = 5)]
        public string name { get; set; }
        public string? location { get; set; }
        public bool? status { get; set; }

        public List<Asset> assets { get; set; }
    }
}

资产 table:

using System.ComponentModel.DataAnnotations;

namespace API.Models
{
    public class Asset : BaseModel
    {
        [Key]
        public int asset_id { get; set; }
        public int? code { get; set; }
        [Required(ErrorMessage = "El campo {0} es obligatorio"), StringLength(10, ErrorMessage = "{0} la longitud debe estar entre {2} y {1}.", MinimumLength = 5)]
        public string? name { get; set; }
        public int iventory_id { get; set; }
        public Inventory inventory { get; set; }
    }
}

然后我添加迁移

dotnet ef migrations add v15

并应用迁移

dotnet ef database update

我收到以下错误:

Cannot insert the value NULL into column 'created_date', table 'WebApp.dbo.Iventories'; column does not allow nulls. UPDATE fails. The statement has been terminated

我不明白为什么会出现此错误。

当我添加?运算符时,数据库不应该接受空值吗?

请使用这些

public class BaseModel
{
    public BaseModel()
    {
        created_date = DateTime.Now;
    }

    [DataType(DataType.DateTime)]
    public DateTime? created_date { get; set; }
    [DataType(DataType.DateTime)]
    public DateTime? modified_date { get; set; }

}

public class BaseModel
{
    public BaseModel()
    {
        created_date = DateTime.Now;
    }

    public Nullable<DateTime> created_date { get; set; }
    public Nullable<DateTime> modified_date { get; set; }

}

I uplaod sample code in git, just change ConnectionString