【问题标题】:The SqlParameterCollection only accepts non-null Parameter type objectsSqlParameterCollection 只接受非空参数类型对象
【发布时间】:2020-03-26 01:16:20
【问题描述】:

我正在尝试在 Entity Framework Core 中使用存储过程。执行存储过程时,我传递了两个输入参数和一个输出参数。我不断收到此错误:

SqlParameterCollection 只接受非空的 SqlParameter 类型对象,不接受 SqlParameter 对象。

这是我的代码:

public string InsertCardsData(DateTime RecordingStartDate, DateTime RecordingEndDate)
{
        try
        {
            // DateTime DRecEndDate = Convert.ToDateTime(RecordingEndDate);
            DateTime DRecEndDate = RecordingEndDate.AddDays(1);

            var RecordStartDate = new SqlParameter
            {
                ParameterName = "RecordingStartDate",
                Value = RecordingStartDate,
                Direction = ParameterDirection.Input
            };

            var RecordEndDate = new SqlParameter
            {
                ParameterName = "RecordingEndDate",
                Value = DRecEndDate,
                Direction = ParameterDirection.Input
            };

            var RecordCount = new SqlParameter
            {
                ParameterName = "RecLoadCount",
                Direction = ParameterDirection.Output
            };

            var SQL = "Exec Recload_InsertPrimeExtract @RecordingStartDate, @RecordingEndDate, @RecLoadCount OUT";
            var result = _context.Database.ExecuteSqlRaw(SQL, RecordStartDate, RecordEndDate, RecordCount);
            var RecordCountValue = RecordCount.Value.ToString();

            return RecordCountValue;
        }
        catch (Exception ex)
        {
            return "";
        }
}

我会放一个有意义的catch语句,但是现在,我在catch语句中放了一个断点,就会出现上述错误。

我们将不胜感激。

【问题讨论】:

  • 不是您的问题,但您为什么要这样做DateTime DRecEndDate = Convert.ToDateTime(RecordingEndDate) 您正在将日期时间转换为日期时间?另外,为什么要返回一个明显是数字的计数的字符串
  • 对不起,我修复了上面的代码。我之前在传递字符串,然后我更改为 DateTime。
  • 您是在声明using System.Data.SqlClient 还是using Microsoft.Data.SqlClient;
  • 尝试将其分解为minimal reproducible example。您的 using 语句在哪里?

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


【解决方案1】:

您的问题很可能是由breaking change in EF Core 3 引起的,当它应该是using Microsoft.Data.SqlClient 时声明using System.Data.SqlClient

为什么

Microsoft.Data.SqlClient 是 SQL 的旗舰数据访问驱动程序 服务器向前发展,System.Data.SqlClient 不再是焦点 的发展。一些重要的功能,例如始终加密,是 仅适用于Microsoft.Data.SqlClient

进一步了解

如果你的代码直接依赖于System.Data.SqlClient,你 必须改为引用Microsoft.Data.SqlClient;作为 两个包保持了非常高的 API 兼容性,这 应该只是一个简单的包和命名空间更改。

github上的相关问题

【讨论】:

  • 我使用的是 System.Data.SQLClient。一旦我更改为 Microsoft.Data.SqlClient,我的代码就开始工作了。
猜你喜欢
  • 2012-11-19
  • 2011-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 2018-05-11
相关资源
最近更新 更多