如何将生成的值用于实体的属性,并在请求正文中允许null?
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime ActualReturnDate { get; set; }
对于此JSON请求:
{
"customerId": 1,
"bookId": 1
}
我收到此错误:
SqlException: Cannot insert the value NULL into column 'ActualReturnDate', table 'TestAPI.Database.LibraryDatabase.dbo.Borrows'; column does not allow nulls. INSERT fails.
The statement has been terminated
控制器:
// POST: api/Borrows
[ResponseType(typeof(Borrow))]
public IHttpActionResult PostBorrow(Borrow borrow)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Borrows.Add(borrow);
更新:使用模型构建器尝试将列默认设置为日期时间。
modelBuilder.Entity<Borrow>()
.Property(b => b.ActualReturnDate)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);