簡體   English   中英

模型中的可選nullable DateTime值

[英]optional nullable DateTime value in Model

這是我的模型:

public class Person {
    public int PersonId {get;set;}
    public string Name {get;set;}

    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime? BirthDate {get;set; }
}

在我的控制器中,我希望讓DateTime屬性值是可選的,換句話說,用戶可以輸入或不輸入該屬性的值。
我怎樣才能做到這一點 ?

編輯
dbContext類:

public class MyDbContext : DbContext
{
    public MyDbContext() : base("DefaultConnection")
    {
    }
   public DbSet<Person> Persons { get; set; }
}

我的動作方法:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "PersonId,Name,BirthDate")] Person person)
{
    if (ModelState.IsValid)
    {
        db.Persons.Add(person);
        db.SaveChanges(); // error is thrown
        return RedirectToAction("Index");
    }

    return View(person);
}

異常(嘗試創建具有空DateTime值的記錄時拋出):

An exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll but was not handled in user code

Additional information: An error occurred while updating the entries. See the inner exception for details.

內部證據:

Exception:Thrown: "The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated." (System.Data.SqlClient.SqlException)
A System.Data.SqlClient.SqlException was thrown: "The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated."
Time: 07/14/2015 08:41:59 ب.ظ
Thread:Worker Thread[3028]

Exception:Caught: "Culture is not supported." (System.Globalization.CultureNotFoundException)
A System.Globalization.CultureNotFoundException was caught: "Culture is not supported."
Time: 07/14/2015 08:41:42 ب.ظ
Thread:<No Name>[8284]

注意:
現在我發現,如果我不使用自定義活頁夾和文化,一切都會很好。

System.Data.Entity.Infrastructure.DbUpdateException指示該值正好傳遞給您的控制器,但您的數據層認為該值是必需的。 檢查您的架構,以確保此列可為空。

我不知道這是否是正確的解決方案:
在SQL Server 2014中將數據類型從datetime更改為datetime2后,它可以工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM