ADO.NET - The Size property has an invalid size of 0

前端 未结 10 993
小蘑菇
小蘑菇 2020-12-14 13:41

I\'m trying to get output value from DB via ADO.NET. There\'s a client code:

    using (var connection = new SqlConnection(ConnectionString))
    {
                


        
相关标签:
10条回答
  • 2020-12-14 14:21

    Everyone's answer was about as clear as mud to me. Maybe this will help someone now that I found what worked.

    Need to add size to the parameter

            DynamicParameters Params = new DynamicParameters();
            Params.Add("@ProfileID", ProfileID);
            Params.Add("@CategoryName", CategoryName);
            Params.Add("@Added", dbType: DbType.String, direction: ParameterDirection.Output,size:10);
    
            db.Execute(sql, Params, commandType: CommandType.StoredProcedure, commandTimeout: 60);
    
            var Added = Params.Get<string>("@Added");
    
    0 讨论(0)
  • 2020-12-14 14:21

    Also, you can get the actual size of the parameters by inspecting the sproc with this little command:

    SqlCommandBuilder.DeriveParameters(yourCommand)
    

    and then just foreach your way through the parameters collection.

    0 讨论(0)
  • 2020-12-14 14:23

    you have to set Size for parameter output

    using (var connection = new SqlConnection(ConnectionString))
    {
        connection.Open();
        SqlCommand command = new SqlCommand("pDoSomethingParamsRes", connection);
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.Add("@i", 1);
        var outParam = new SqlParameter("@out", SqlDbType.VarChar);
        outParam.Direction = ParameterDirection.Output;
        outParam.Size = 50; // this is example
        command.Parameters.Add(outParam);
        command.ExecuteNonQuery();
        Console.WriteLine(command.Parameters["@out"].Value.ToString());
    }
    
    0 讨论(0)
  • 2020-12-14 14:29

    I had the same error and below is my code that works

    cmd.Parameters("@ProjectKey").SqlDbType = SqlDbType.NVarChar
    cmd.Parameters("@ProjectKey").Size = 150
    cmd.Parameters("@ProjectKey").Direction = ParameterDirection.InputOutput
    cmd.ExecuteNonQuery()
    
    0 讨论(0)
  • 2020-12-14 14:32

    Parameter Size is required for variable size Output parameters. Generally ADO.NET decides the size of the parameter based on the Value assigned to the parameter (hence it is optional), but in output parameter since no value is Set, you need provide the size required for the parameter

    Set the Parameter size to size of the output variable from the DB... Say 50

    outParam.Size = 50;
    
    0 讨论(0)
  • 2020-12-14 14:33

    I'm not sure if this is the same problem i've had before, but using a byte for a parameter can sometimes lead to this error.

    Try this. Explicitly declare the i parameter as a variable. THEN assign it's value with the Value property.

    0 讨论(0)
提交回复
热议问题