How to return results from SQL SELECT raw Query?

时间:2019-01-18 19:04:55

标签: c# sql .net-core

I have a method in my controller class that is supposed to return the results from a raw SQL query inside the method. 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.

Does anyone know what I am missing to return multiple column names for this SQL query and method? 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.

1 个答案:

答案 0 :(得分:4)

您可以为查询结果创建一个类

  let body = new FormData();
  body.append('name',this.actorName); 
  body.append('country',this.actorCountry );
  body.append('first_movie',this.actorFirstMovie);
  body.append('best_movie',this.actorBestMovie);
  body.append('imdb_best_movie',this.actorImdbBestMovie);
  body.append('file',this.image);