我是MVC的新手,当我尝试保存到数据库时,我收到以下错误
将datetime2数据类型转换为日期时间数据类型会导致超出范围的值
型号:
[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);
}
答案 0 :(得分:2)
在SQL Server中,datetime
不能为空(除非您将其标记为此)并且不能在1753年1月1日之前。您违反了其中一个约束。我没有看到您在DateTime
对象中设置OrderStatus
属性。我建议那是你的问题。
您可以使用以下内容在数据库中为该特定列设置默认日期:
ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETDATE() FOR YourColumn
但是,我不建议这样做,因为在我看来,应该在应用程序中明确声明逻辑,因为你在数据库中隐藏逻辑。