【问题标题】:Pass Array Parameter in SqlCommand with additional parameters使用附加参数在 SqlCommand 中传递数组参数
【发布时间】:2020-09-22 18:03:13
【问题描述】:

我查看了几个将数组作为 sql 参数传递的示例,但我还需要传递一些额外的参数。我正在使用数组来过滤我的插入,并传入更新的值。下面的代码可以编译,但是当我运行它时,我收到一个关于链接服务器的奇怪错误。这没有任何意义,因为我只更新当前服务器上的一个表。

public List<InvoiceForEmail> RejectInvoices(
    List<int> invoiceIds,
    string reason,
    string ADUsername)
{
    if (invoiceIds == null || invoiceIds.Count <= 0) throw new ArgumentOutOfRangeException(nameof(invoiceIds));
    if (reason == null) throw new ArgumentNullException(nameof(reason));

    int rowsUpdated;

    using (var context = new ShopAPDbContext())
    {
        var cmd = new SqlCommand(@"
                UPDATE  ShopAP.dbo.ShopPO
                SET     ModifiedDate = GETDATE(),
                        RejectedDate = GETDATE(),
                        RejectedReason = @Reason,
                        RejectedBy = @RejectedBy,
                        FailedReason = @FailedReason
                WHERE   ID IN ({Id})
                    AND ApprovalDate IS NULL
                    AND RejectedDate IS NULL");
        cmd.AddArrayParameters("Id", invoiceIds);
        cmd.Parameters.Add(new SqlParameter("@Reason", reason));
        cmd.Parameters.Add(new SqlParameter("@RejectedBy", ADUsername));
        cmd.Parameters.Add(new SqlParameter("@FailedReason", DBNull.Value));

        rowsUpdated = context.Database.ExecuteSqlCommand(cmd.ToString());

        cmd.Dispose();
    }

    if (rowsUpdated == 0)
        return null;

    return GetInvoicesForEmail(invoiceIds);
}

我在尝试执行时收到此错误:

System.Data.SqlClient.SqlException 

 HResult=0x80131904
  Message=Could not find server 'System' in sys.servers. Verify that the correct server name was specified. If necessary, execute the stored procedure sp_addlinkedserver to add the server to sys.servers.
  Source=.Net SqlClient Data Provider
  StackTrace:
<Cannot evaluate the exception stack trace>

这里是数组的扩展方法。

using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

namespace ShopAP.API.Data.Extensions
{
    public static class SqlCommandExt
    {

        /// <summary>
        /// This will add an array of parameters to a SqlCommand. This is used for an IN statement.
        /// Use the returned value for the IN part of your SQL call. (i.e. SELECT * FROM table WHERE field IN ({paramNameRoot}))
        /// </summary>
        /// <param name="cmd">The SqlCommand object to add parameters to.</param>
        /// <param name="paramNameRoot">What the parameter should be named followed by a unique value for each value. This value surrounded by {} in the CommandText will be replaced.</param>
        /// <param name="values">The array of strings that need to be added as parameters.</param>
        /// <param name="dbType">One of the System.Data.SqlDbType values. If null, determines type based on T.</param>
        /// <param name="size">The maximum size, in bytes, of the data within the column. The default value is inferred from the parameter value.</param>
        public static SqlParameter[] AddArrayParameters<T>(this SqlCommand cmd, string paramNameRoot, IEnumerable<T> values, SqlDbType? dbType = null, int? size = null)
        {
            /* An array cannot be simply added as a parameter to a SqlCommand so we need to loop through things and add it manually. 
             * Each item in the array will end up being it's own SqlParameter so the return value for this must be used as part of the
             * IN statement in the CommandText.
             */
            var parameters = new List<SqlParameter>();
            var parameterNames = new List<string>();
            var paramNbr = 1;
            foreach (var value in values)
            {
                var paramName = string.Format("@{0}{1}", paramNameRoot, paramNbr++);
                parameterNames.Add(paramName);
                SqlParameter p = new SqlParameter(paramName, value);
                if (dbType.HasValue)
                    p.SqlDbType = dbType.Value;
                if (size.HasValue)
                    p.Size = size.Value;
                cmd.Parameters.Add(p);
                parameters.Add(p);
            }

            cmd.CommandText = cmd.CommandText.Replace("{" + paramNameRoot + "}", string.Join(",", parameterNames));

            return parameters.ToArray();
        }
    }
}

【问题讨论】:

  • 表有触发器吗?
  • 无触发器。当我通过 SSMS 运行时,查询有效。
  • cmd.ToString()的结果是什么?
  • 听起来可能是 ConnectionString 问题。您是否验证了您的连接字符串有效?
  • 我用于其他几种方法的相同连接字符串,它们都有效。 cmd.ToString() 给了我一个有效的查询字符串。

标签: c# sql .net sql-server entity-framework


【解决方案1】:

Database.ExecuteSqlCommand 接受一个字符串和一个参数列表,而不是一个 SqlCommand 对象。

您无法传递 SqlCommand,因此您尝试 .ToString() 返回字符串的 SqlCommand:

System.Data.SqlClient.SqlCommand

所以这个

rowsUpdated = context.Database.ExecuteSqlCommand(cmd.ToString());

等价于

rowsUpdated = context.Database.ExecuteSqlCommand("System.Data.SqlClient.SqlCommand");

这是导致错误的原因,因为这看起来像是使用链接服务器的 4 部分名称。

应该是这样的:

var sql = cmd.CommandText;
var parameters = cmd.Parameters.Cast<SqlParameter>().ToArray();
db.Database.ExecuteSqlCommand(sql, parameters);

【讨论】:

    猜你喜欢
    • 2023-03-24
    • 1970-01-01
    • 2014-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    相关资源
    最近更新 更多