【问题标题】:Conversion of a datetime2 data type to a datetime data error将 datetime2 数据类型转换为 datetime 数据错误
【发布时间】: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();

标签: c# datetime


【解决方案1】:

在 SQL Server 中,datetime 不能为 null(除非您将其标记为 null)并且不能在 1753 年 1 月 1 日之前。您违反了这些约束之一。我没有看到您在 OrderStatus 对象中设置 DateTime 属性。我认为这是你的问题。

您可以使用以下内容在数据库中为该特定列设置默认日期:

ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETDATE() FOR YourColumn

但是我不建议这样做,因为您将逻辑隐藏在数据库中,而我认为应该在应用程序中显式声明它。

【讨论】:

    猜你喜欢
    • 2013-04-24
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 2011-04-07
    相关资源
    最近更新 更多