[英]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. 在我的控制器中,我希望让DateTime属性值是可选的,换句话说,用户可以输入或不输入该属性的值。
how can i do this ? 我怎样才能做到这一点 ?
EDIT : 编辑 :
DbContext class: dbContext类:
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): 异常(尝试创建具有空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.
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. System.Data.Entity.Infrastructure.DbUpdateException
指示该值正好传递给您的控制器,但您的数据层认为该值是必需的。 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. 在SQL Server 2014中将数据类型从datetime更改为datetime2后,它可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.