C# 将存储过程的结果作为IEnumerable返回
我不知道如何正确地完成这个-我有一个存储的进程,我想返回一个IEnumberable的结果C# 将存储过程的结果作为IEnumerable返回,c#,sql,ienumerable,C#,Sql,Ienumerable,我不知道如何正确地完成这个-我有一个存储的进程,我想返回一个IEnumberable的结果 public IEnumerable GetGuids(int id) { SqlCommand _command = new SqlCommand("storedProc"); _command.CommandType = CommandType.StoredProcedure; _command.Parameters.AddWithValue
public IEnumerable GetGuids(int id)
{
SqlCommand _command = new SqlCommand("storedProc");
_command.CommandType = CommandType.StoredProcedure;
_command.Parameters.AddWithValue("@ItemID", id);
return _command.ExecuteReader();
}
运行此命令时,我得到:
ExecuteReader:Connection属性尚未初始化。
您的SqlCommand没有相应的连接。或使用:
_command.Connection = conn;
或者通过使用
conn.CreateCommand(…)
像这样传递连接对象GetGuids(int-id,SqlConnection-conn)
使用SqlConnection初始化SqlCommand,并确保SqlConnection已打开。 在此之后,ExecuteReader提供了一个SqlDataReader,您必须通读该读取器并读取值
SqlDataReader reader = _command.ExecuteReader();
while(reader.Read()
{
// readvalue of reader["columname"] and insert into a list or yield return it.
}
您的
SqlCommand
需要SqlConnection
。检查构造函数的第二个参数。您应该阅读一些关于如何使用SqlCommand的教程。我不认为您真的想返回_command.ExecuteReader()-
SqlDataReader reader = _command.ExecuteReader();
while(reader.Read()
{
// readvalue of reader["columname"] and insert into a list or yield return it.
}