从列表WCF获取所有数据

问题描述 投票:0回答:1

我将一个字符串传递给我的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

c# loops wcf arraylist
1个回答
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

这种方法可以节省您每次在循环成本有效时创建的额外数据库调用和连接。

© www.soinside.com 2019 - 2024. All rights reserved.