[英]How to return results from SQL SELECT raw Query?
I have a method in my controller class that is supposed to return the results from a raw SQL query inside the method. 我的控制器类中有一个方法,应该从该方法内部的原始SQL查询返回结果。 The problem is I can't pull return more than one column result to the list in a query that is supposed to return multiple column results.
问题是我无法在应该返回多列结果的查询中将返回的多列结果拉到列表中。
I know that the problem has to do with how I am adding to the results list during the Read, but I am unsure how to structure this properly to return multiple values. 我知道问题与在读取过程中如何添加到结果列表有关,但是我不确定如何正确构造此结构以返回多个值。
Here is my current method: 这是我目前的方法:
public IActionResult Search ([FromRoute]string input)
{
string sqlcon = _iconfiguration.GetSection("ConnectionStrings").GetSection("StringName").Value;
List<string> results = new List<string>();
using (var con = new SqlConnection(sqlcon))
{
using (var cmd = new SqlCommand()
{
CommandText = "SELECT u.UserID, u.User FROM [dbo].[Users] u WHERE User = 'Value';",
CommandType = CommandType.Text,
Connection = con
})
{
con.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
results.Add(reader.GetString(0));
}
con.Close();
return Ok(new Search(results));
}
}
}
}
The SQL query is supposed to return the UserID
and User based on the entered User, however, only the User gets returned here. SQL查询应该根据输入的用户返回
UserID
和用户,但是,此处仅返回用户。
Does anyone know what I am missing to return multiple column names for this SQL query and method? 有谁知道我缺少为此SQL查询和方法返回多个列名称的信息? Any advice would be greatly appreciated.
任何建议将不胜感激。
FYI, I can't use a stored procedure here, I do not have permission to create an SP on this database. 仅供参考,我在这里不能使用存储过程,我没有在该数据库上创建SP的权限。
You can create a class for the results of the Query 您可以为查询的结果创建一个类
public class ClassForResults(){
public int UserID { get; set; };
public string User { get; set; }
}
public IActionResult Search ([FromRoute]string input)
{
string sqlcon = _iconfiguration.GetSection("ConnectionStrings").GetSection("StringName").Value;
List<ClassForResults> results = new List<ClassForResults>();
using (var con = new SqlConnection(sqlcon))
{
using (var cmd = new SqlCommand()
{
CommandText = "SELECT u.UserID, u.User FROM [dbo].[Users] u WHERE User = 'Value';",
CommandType = CommandType.Text,
Connection = con
})
{
con.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
ClassForResults result = new ClassForResults();
result.UserID = reader.GetInt(0);
result.User = reader.GetString(1);
results.Add(result);
}
con.Close();
return Ok(new Search(results));
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.