System.Data.SqlClient.SqlException: 无法将值 NULL 插入到 AspnetCore Web 中的列中 Api

System.Data.SqlClient.SqlException: Cannot insert the value NULL into column in AspnetCore Web Api

我正在 AspNetCore 中创建网站 api。我想在 sql 服务器中设置默认 DateTime 值。以下是创建 Web Api.

的方法

控制器:

[HttpPost]
        [Route("Insert/PartyAddress")]
        public async Task<IActionResult> PostPartyAddressAsync([FromBody] PartyAddress partyAddress)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);
            var result = await _repo.PostPartyAddressAsync(partyAddress);
            return Ok(result);
        }

存储库逻辑:

public async Task<bool> PostPartyAddressAsync(PartyAddress partyAddress)
        {
            try
            {
                TblPartyAddress tblPartyAddress = new TblPartyAddress();
                tblPartyAddress.PartyId = partyAddress.PartyId;
                tblPartyAddress.AddressLine1 = partyAddress.AddressLine1;
                tblPartyAddress.AddressLine2 = partyAddress.AddressLine2;
                tblPartyAddress.Pincode = partyAddress.Pincode;
                tblPartyAddress.City = partyAddress.City;
                tblPartyAddress.State = partyAddress.State;
                tblPartyAddress.Country = partyAddress.Country;
                tblPartyAddress.PersonName = partyAddress.PersonName;
                tblPartyAddress.Email = partyAddress.Email;
                tblPartyAddress.ContactNo = partyAddress.ContactNo;
                tblPartyAddress.IsDefault = partyAddress.IsDefault;
                tblPartyAddress.IsActive = partyAddress.IsActive;

                await ctx.Context.tblPartyAddresses.AddAsync(tblPartyAddress);
                ctx.Context.Entry(tblPartyAddress).State = EntityState.Added;
                await ctx.Context.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

映射Class

[Table("tblPartyAddress")]
    public class TblPartyAddress
    {
        [Key]
        [Column("Id")]
        [Required]
        public int Id { get; set; }
        [Column("PartyId")]
        [Required]
        public int PartyId { get; set; }
        [Column("AddressLine1")]
        [Required]
        public string AddressLine1 { get; set; }
        [Column("AddressLine2")]
        public string AddressLine2 { get; set; }
        [Column("Pincode")]
        [MaxLength(50)]
        [Required]
        public string Pincode { get; set; }
        [Column("City")]
        [MaxLength(50)]
        public string City { get; set; }
        [Column("State")]
        [MaxLength(50)]
        public string State { get; set; }
        [Column("Country")]
        [MaxLength(50)]
        public string Country { get; set; }
        [Column("PersonName")]
        [MaxLength(50)]
        [Required]
        public string PersonName { get; set; }
        [Column("Email")]
        [MaxLength(50)]
        [Required]
        public string Email { get; set; }
        [Column("ContactNo")]
        [MaxLength(20)]
        [Required]
        public string ContactNo { get; set; }
        [Column("IsDefault")]
        [Required]
        public bool IsDefault { get; set; }
        [Column("IsActive")]
        [Required]
        public bool IsActive { get; set; }
        [Column("CreatedDate")]
        public DateTime? CreatedDate { get; set; } 
        [Column("ModifiedDate")]
        public DateTime? ModifiedDate { get; set; }
    }

但我在向 Table 插入数据时遇到以下异常。

{Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'CreatedDate', table 'AasthaSales.dbo.tblPartyAddress'; column does not allow nulls. INSERT fails.
    The statement has been terminated.
       at System.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__108_0(Task`1 result)
       at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.<ExecuteAsync>d__17.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.<ExecuteAsync>d__32.MoveNext()
       --- End of inner exception stack trace ---
       at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.<ExecuteAsync>d__32.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.<ExecuteAsync>d__10.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.<ExecuteAsync>d__7`2.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.<SaveChangesAsync>d__61.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.<SaveChangesAsync>d__59.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at Microsoft.EntityFrameworkCore.DbContext.<SaveChangesAsync>d__48.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

如有任何疑问,请随时提出。

我们将不胜感激。

可空 DateTime 显然会映射到允许空值的列,因此唯一可能的解释是在某些时候它是 而不是 DateTime? 然后你把它变成了一个,或者你在它上面有 Required 属性并删除了它。无论哪种情况,您都需要进行新的迁移以将这些更改传播回数据库。

但是,对于这种特定情况,像您的 CreatedDate 属性 这样的东西应该是 non-nullable 并且只需要一个默认设置:

public DateTime CreatedDate { get; set; } = DateTime.UtcNow;