如何处理对具有生成属性的实体的请求

时间:2019-06-26 14:25:29

标签: entity-framework

如何将生成的值用于实体的属性,并在请求正文中允许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);

0 个答案:

没有答案