【发布时间】:2015-09-08 14:16:02
【问题描述】:
我是 MVC 新手,尝试保存到数据库时出现以下错误
将 datetime2 数据类型转换为 datetime 数据类型导致值超出范围
型号:
[Required]
[Display(Name = "Date")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime Date { get; set; }
控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ReorderContactLenses reorderContactLenses)
{
// If Model State is Valie
if (ModelState.IsValid)
{
// Generateds an OrderId
reorderContactLenses.OrderId = Guid.NewGuid();
// Checks if user is logged in
if (User.Identity.IsAuthenticated)
{
// Gets the UserId
string userId = User.Identity.GetUserId();
// Finds PatientId where the Patient.UserId matchs that of the logged in User and assigns the PatientId to reorderContactLenses.PatientId
reorderContactLenses.PatientId = (from d in db.Patients
where d.UserId == userId
select d.PatientId).Single();
}
// Sets the reorderContactLense Date to todays Date
reorderContactLenses.Date = DateTime.Now.Date;
//Adds reorderContactLenses to the database
db.ReorderContactLenses.Add(reorderContactLenses);
// Initilises and Order Status
OrderStatus orderStatus = new OrderStatus();
// Generates an Id for the Order Status
orderStatus.OrderStatusId = new Guid();
// Assigns the reorderContactLenses OrderId to Order Status OrderId
orderStatus.OrderId = reorderContactLenses.OrderId;
// Sets the Ordered Bool to false
orderStatus.Ordered = false;
// Adds the Order Status to the Database
db.OrderStatus.Add(orderStatus);
//Saves the changes
db.SaveChanges();
return RedirectToAction("Index");
}
ConfigureCreateView(reorderContactLenses);
return View(reorderContactLenses);
}
【问题讨论】:
-
你在哪一行出错
-
在 SQL Server 中,
datetime不能为空(除非您将其标记为空)并且不能早于 1753 年 1 月 1 日。您违反了这些约束之一。您需要设置断点并单步执行代码以找出问题所在。 -
@MicrosoftDN
db.SaveChanges();