从列表WCF中获取所有数据

时间:2019-03-08 10:35:32

标签: c# loops wcf arraylist

我这样将字符串传递给WCF服务

http://localhost:49854/Service1.svc/rest/getData/station_number=("31098","31508","31273")

我的IService:

[OperationContract]
    [WebInvoke(Method = "*" ,ResponseFormat = WebMessageFormat.Json,RequestFormat = WebMessageFormat.Json, UriTemplate = "getData/station_number=({number})")]
    IEnumerable<Data> getData(string number);

然后,该字符串将由,切成小块,然后添加到列表中,此后,我将循环遍历该列表,然后获取与列表成员匹配的数据,如下所示:

public class Service1 : IService1
{
    public IEnumerable<Data> getData(string number)
    {
        string cs = ConfigurationManager.ConnectionStrings["Bokeh_data"].ConnectionString;
        List<string> new_list = new List<string>();
        new_list = number.Split(',').ToList();
        List<Data> data_cont = new List<Data>();
        Data dt = new Data();
        for (var i = 0; i< new_list.Count; i++)
        {
            using (SqlConnection conn = new SqlConnection(cs))
            {
                SqlCommand cmd = new SqlCommand("GetData_byvalue", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@number", SqlDbType.VarChar, 50).Value = new_list[i];
                conn.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                while(reader.Read())
                {
                    dt.bike_number = reader["Bike_number"].ToString();
                    dt.start_station = reader["Start_station"].ToString();
                    dt.start_station_num = reader["Start_station_numb"].ToString();
                    data_cont.Add(dt);
                }
            }

        }
        return data_cont;
    }

我的程序:

CREATE PROCEDURE GetData_byvalue(@number nvarchar(50))
AS
BEGIN
 SELECT * FROM data WHERE Start_station_num = @number
END

但是我一次只能获得最后一个Start_station_num,例如"31273"(我的表中有全部三个Start_station_num),可能是因为我的Loop或字符串错误吗? >

这是我从WCF得到的: unexpected result

1 个答案:

答案 0 :(得分:0)

使用以下功能从您用逗号分隔的ID中获取行

Create FUNCTION dbo.CSVToNvarcharTable (@InStr NVARCHAR(MAX))
    RETURNS @TempTab TABLE (id NVARCHAR(MAX) NOT NULL)
    AS
    BEGIN
        ; -- Ensure input ends with comma
        SET @InStr = REPLACE(@InStr + ',', ',,', ',');
        DECLARE @SP INT;
        DECLARE @VALUE NVARCHAR(MAX);
        WHILE PATINDEX('%,%', @InStr) <> 0
        BEGIN
            SELECT @SP = PATINDEX('%,%', @InStr);
            SELECT @VALUE = LEFT(@InStr, @SP - 1);
            SELECT @InStr = STUFF(@InStr, 1, @SP, '');
            INSERT INTO @TempTab
            (
                id
            )
            VALUES  (LTRIM(RTRIM(@VALUE))); -- Ensure input don't have trailing 0's
        END;
        RETURN;
    END;

    GO

然后将包含逗号分隔ID的字符串传递给DB

喜欢

CREATE PROCEDURE GetData_byvalue(@number nvarchar(50))
AS
BEGIN

 SELECT * FROM data INNER JOIN dbo.CSVToNvarcharTable(@number) AS funcResult
ON Start_station_num =funcResult.id
END

此方法可节省每次循环创建的额外数据库调用和连接,节省成本。