【问题标题】:System.Data.SqlClient.SqlException: Cannot insert the value NULL into column in AspnetCore Web ApiSystem.Data.SqlClient.SqlException:无法将值 NULL 插入 AspnetCore Web Api 中的列
【发布时间】:2018-03-28 08:49:36
【问题描述】:

我在 AspNetCore 中创建 web api。我想在 sql Server 中设置默认的 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;
            }
        }

映射类

[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; }
    }

但我在将数据插入表中遇到以下异常。

{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)

如果有人有疑问,请随时询问。

我们将不胜感激。

【问题讨论】:

    标签: sql datetime asp.net-core-webapi sqlexception


    【解决方案1】:

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

    但是,对于这种特殊情况,您的 CreatedDate 属性应该是不可为空的,并且只需设置一个默认设置:

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

    【讨论】:

      猜你喜欢
      • 2016-01-11
      • 1970-01-01
      • 1970-01-01
      • 2013-02-27
      • 2021-10-31
      • 2012-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多