“SqlParameterCollection only accepts non-null SqlParameter type objects, not String objects”

后端 未结 8 1921
暗喜
暗喜 2021-01-04 07:23

I keep getting the exception

The SqlParameterCollection only accepts non-null SqlParameter type objects, not String objects

, while execut

相关标签:
8条回答
  • 2021-01-04 07:56

    I replaced my reference to System.Data.SqlClient with Microsoft.Data.SqlClient corrected the using statements and my problems went away

    In my .csproj I now have

      <ItemGroup>
        <PackageReference Include="Microsoft.Data.SqlClient" Version="1.1.2" />
        <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.3" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.3" />
      </ItemGroup>
    

    But I also found I had use of the following scenario where I created a System.Data.SqlClient.SqlParameter

        public static List<T> RunQuery<T>(ApiDbContext context, string query, Func<DbDataReader, T> map, params SqlParameter[] parameters)
        {
            var cn = context.Database.GetDbConnection();
            var oldState = cn.State;
            if (cn.State.Equals(ConnectionState.Closed)) { cn.Open(); }
    
            using (var command = cn.CreateCommand())
            {
                command.CommandText = query;
                command.CommandType = CommandType.Text;
                foreach (var param in parameters)
                {
                    var p = new System.Data.SqlClient.SqlParameter
                    {
                        ParameterName = param.ParameterName, Value = param.Value, SqlDbType = param.SqlDbType
                    };
                    command.Parameters.Add(p);
                }
                if (cn.State.Equals(ConnectionState.Closed)) { cn.Open(); }
                var entities = new List<T>();
                using (var result = command.ExecuteReader())
                {
                    while (result.Read())
                    {
                        entities.Add(map(result));
                    }
                }
    
                if (oldState.Equals(ConnectionState.Closed) && cn.State == ConnectionState.Open) { cn.Close(); }
                return entities;
            }
        }
    
    0 讨论(0)
  • 2021-01-04 08:01

    Try below

    comm.Parameters.Add("@author", SqlDbType.VarChar);
    comm.Parameters["@author"].Value = dataGridView1.Rows[i].Cells[0].Value.ToString();
    
    0 讨论(0)
提交回复
热议问题