如何在列表<>中捕获此存储过程的结果?

时间:2015-05-02 08:27:55

标签: c# sql-server tsql stored-procedures linq-to-sql

我已经和它搏斗了至少3个小时,而且我对C#有些新手,尤其是从SQL Server中的存储过程返回多行时。

我想返回存储过程的结果:

create procedure ingredientNames_givenDishId
    @dishid inT
AS
    SELECT 
        a.ingredientname --given dish id, return ingredientnames     
    FROM 
        dbo.purple_ingredients a 
    JOIN 
        dbo.purple_dish_ingredients b ON a.ingredientid = b.ingredientid
    WHERE
        b.dishid = @dishid

这是我在SQL Server中执行相同过程时的结果,其中10为dishid: enter image description here

我的C#代码:

private void btnIngs3FromDishId_Click(object sender, EventArgs e) {
    List<Ingredient> someIngs = new List<Ingredient>();

    Purple_DataClasses1DataContext dbContextCreateMenu = 
        new Purple_DataClasses1DataContext(DataHandler.theConnectionString);
    foreach (var row in dbContextCreateMenu.ingredientNames_givenDishId(10))
            MessageBox.Show(row.ToString());

我也尝试过:

     var thing = dbContextCreateMenu.ingredientNames_givenDishId(10);
     var anotherThing = thing.AsEnumerable();
        foreach (var subthing in anotherThing)

当我设置断点并将鼠标悬停在“anotherThing”上时,最后一个示例实际显示了3个字符串值: looks like I could get the data!

我可以用鼠标向下钻取并查看字符串值一次,然后我会 收到后续尝试的通知:{“查询结果不能多​​次枚举。”}

非常感谢任何帮助。谢谢!

@Enigmativity:这有帮助,并且实施起来非常简单。这就是我最终得到的结果,这很好用:

var thing= dbContextCreateMenu.ingredientNames_givenDishId(10);
var anotherThing = thing.ToList();
MessageBox.Show(anotherThing.ElementAt(0).ingredientname);

@Sharag&amp; marc_s:让这个老方法也可以工作!!非常感激。其他一些新用户需要注意的一些事项:我需要这一行:

cmd.CommandType = CommandType.StoredProcedure; 

另外我需要在这一行中将@dishid显式设置为int,否则它将被编译器视为Object:

cmd.Parameters.AddWithValue("@dishid", Convert.ToInt32(aValue));

2 个答案:

答案 0 :(得分:1)

我不是LINQ的专家,但是如果你想要一直有效的旧方法,那就在这里:

List<String> lt = new List<string>();    
     try{

         if (con.State == System.Data.ConnectionState.Closed)
              con.Open();
               cmd.CommandText = qr;\\the query 
                SqlDataAdapter adp = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                adp.Fill(dt);
             for(int i=0;i<dt.Rows.Count;i++)
               {lt.Add(dt.Rows[i][0].toString());}
            }
            catch (SqlException exc)
            { MessageBox.Show(exc.Message);  }

答案 1 :(得分:1)

在C#端,您可以使用阅读器,数据表,适配器进行访问。

数据阅读器的示例代码如下所示

SqlConnection connection = new SqlConnection(ConnectionString);

command = new SqlCommand("TestProcedure", connection);
command.CommandType = System.Data.CommandType.StoredProcedure;
connection.Open();

reader = command.ExecuteReader();

List<Test> TestList = new List<Test>();

Test test;

while (reader.Read())
{
    test = new Test();
    test.ID = int.Parse(reader["ID"].ToString());
    test.Name = reader["Name"].ToString();

    TestList.Add(test);
}
相关问题