【问题标题】:Dapper SqlDateTime overflow using GETDATE() in SQL Server在 SQL Server 中使用 GETDATE() 的 Dapper SqlDateTime 溢出
【发布时间】:2013-11-07 04:48:32
【问题描述】:

我有以下代码,它从表单获取输入并调用存储过程将其存储在数据库中。

 [HttpPost]
 public ActionResult Index(GuestMessage model)
 {
        if (ModelState.IsValid)
        { 
            using(IDbConnection conn = DatabaseAcess.OpenConnection())
            {
                const string storedProcedure = "dbo.InsertMessage";
                conn.Execute(storedProcedure, new GuestMessage { Name = model.Name, Email = model.Email, Message = model.Message }, null, null, CommandType.StoredProcedure);

                return View("ThankYou");
            }
         }
        return View();
}

用户必须填写三个字段,NameE-mailMessage。在数据库中,我使用名为 dbo.Insert Message 的存储函数存储用户从这三个字段输入的数据以及输入时间。

BEGIN
  BEGIN TRAN

  SET NOCOUNT ON;

  DECLARE @GuestID int;
  INSERT INTO Guest(Name, Email) VALUES (@Name, @Email);
  SELECT @GuestID = scope_identity();

  INSERT INTO Message (EntryDate, GuestID, Message, Status) 
  VALUES (GETDATE(), @GuestID, @Message, 2);

  COMMIT TRAN
END

请注意,我没有将输入日期和时间作为输入参数传递给存储过程,因为没有必要这样做。我使用 SQL Server 中的内置函数GETDATE() 来确定用户输入消息的时间。

但是,每当我尝试输入消息时,都会收到以下错误:

SqlDateTime 溢出。必须在 1753 年 1 月 1 日上午 12:00:00 到 9999 年 12 月 31 日晚上 11:59:59 之间

【问题讨论】:

    标签: sql sql-server asp.net-mvc-3 dapper


    【解决方案1】:

    我建议进行以下更改:

    conn.Execute(storedProcedure,
        new { Name = model.Name, Email = model.Email, Message = model.Message },
        commandType: CommandType.StoredProcedure);
    

    唯一的实际变化是我将new GuestMessage { ... } 换成了new { ... }。我怀疑正在发生的是您的GuestMessage 类型具有不需要的附加属性,但它作为参数发送。 DateTime 保留其默认值是“00:00:00.0000000, January 1, 0001”。通过仅交换到 new { ... },我们明确限制我们发送到 NameEmailMessage 的成员,因为这些是唯一定义的内容.

    注意:当使用纯文本时,dapper 确实使用了一些巫术来尝试查看 SQL 中实际使用了哪些参数名称,并且它不会发送任何它知道不知道的东西在 SQL 中引用 - 但是,它不能对存储过程执行此操作。

    【讨论】:

    • 你是对的,我将 new GuestMessage { ... } 更改为 new { ... } 并且它有效。 Dapper 背后有一些巫术,因为我从不将来自 GuestMessage 对象的日期参数传递给存储过程。存储过程甚至不希望看到 DateTime。为了设置日期时间,我使用 SQL 服务器内置函数 GETDATE()。非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多