简体   繁体   中英

optional nullable DateTime value in Model

this is my 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; }
}

in my controller i want let the DateTime property value to be optional, in another word user can enter or not enter the value to this property.
how can i do this ?

EDIT :
DbContext class:

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

my action method :

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

Exception(thrown when trying to create a record with null DateTime value):

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.

inner exeptions:

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]

Note:
right now i figured out that if i don't use custom binder and culture every thing works fine.

System.Data.Entity.Infrastructure.DbUpdateException indicates that the value is being passed to your controller just fine, but your data layer thinks that the value is required. Check your schema to ensure that this column is nullable.

i don't know if this is right solution or not :
after changing data type from datetime to datetime2 in SQL Server 2014, it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM