【问题标题】:How to use DateTime.Now without error inside stored procedure如何在存储过程中使用 DateTime.Now 而不会出错
【发布时间】:2021-01-27 16:41:36
【问题描述】:

我的 Blazor 项目有问题,我在变量中使用了“DateTime.Now”,以便通过存储过程将其插入到我的 sql 数据库中。但我有这个错误消息:'将数据类型 varchar 转换为日期时间时出错。'

我给你存储过程+代码:

ALTER PROCEDURE [dbo].[spNewLog] @Date datetime
AS
insert into dbo.LogChange (Date) values (@Date);

和代码:

LogModel l = new LogModel
            {
                Date = DateTime.Now,
            };
            await _logdb.NewLog(l);

我添加 _logdb.NewLog(LogModel log) :

string sql = "spNewLog @Date ='" + log.Date + "';"
            using (IDbConnection connection = new SqlConnection(connectionString))
            {
                await connection.ExecuteAsync(sql);
            }

另一个编辑:我使用 dapper

【问题讨论】:

  • DateTime.Now 是一个属性。 DateTime 类型映射到 datetime 没有任何问题。 NewLog 是做什么的?看起来它正在将日期转换为字符串而不是使用日期参数
  • 我在标题中进行了编辑,但我在代码中使用了属性
  • 这段代码有什么作用? ADO.NET 不会将 DateTime 转换为字符串。代码正在做它不应该做的事情。您是否正在使用字符串插值来生成查询?
  • 您需要向我们展示 SP 是如何执行的。 _logDb.NewLog() 是做什么的?
  • 这似乎与存储过程无关。请发帖NewLog()

标签: c# sql datetime entity-framework-core


【解决方案1】:

行:

string sql = "spNewLog @Date ='" + log.Date + "';"

生成并执行一个字符串。日期将转换为与服务器区域设置不匹配的本地化字符串。不需要使用这样的代码。

看起来代码正在使用 Dapper,因为 IDbConnection 中没有 ExecuteAsync 方法。 Dapper 旨在消除对字符串连接的需求,并使编写参数化查询更容易。

代码可以改成:

using (var connection = new SqlConnection(connectionString))
{
    await connection.ExecuteAsync("spNewLog",
                                   new {date=log.Date},
                                   commandType: CommandType.StoredProcedure);
}

考虑使用日志库

您可以通过将 .NET Core 的 ILogger 与日志库一起使用来大大简化您的代码。大多数日志库都可以写入数据库表。

例如,Serilog 可以使用Serilog.Sinks.MSSqlServer 写入 SQL Server。这将更容易记录并收集比日期更多的信息。 Serilog 有 Blazor client-side logging to the consolsending the logs to the server 的接收器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 2011-06-21
    • 1970-01-01
    相关资源
    最近更新 更多