Click here to Skip to main content
13,869,102 members
Rate this:
Please Sign up or sign in to vote.
See more:
Guys i have sql query which return Json string in Asp.Net C# i am unable return it please help me out of it. and i dont want to use datareader.

What I have tried:

public Employee Get()
            SqlDataReader reader = null;
            SqlConnection myConnection = new SqlConnection();
            myConnection.ConnectionString = @"Data Source=Demo\SQLEXPRESS;Initial Catalog=DB;User ID=xyz;Password=xyz123;Connection Timeout=1800;";

            SqlCommand sqlCmd = new SqlCommand();
            sqlCmd.CommandType = CommandType.Text;
            string jsonOutputParam = "@jsonOutput";
            //sqlCmd.CommandText = "Create_JSON_ProjectList";
            //sqlCmd.Parameters.Add(jsonOutputParam, SqlDbType.NVarChar, -1).Direction = ParameterDirection.Output;
            sqlCmd.Connection = myConnection;
            string st = "select projectName from QryProjectWithDepartmentDetails ORDER BY projectName DESC FOR JSON PATH, WITHOUT_ARRAY_WRAPPER";
            sqlCmd = new SqlCommand(st, myConnection);
            reader = sqlCmd.ExecuteReader();
            Employee emp = null;
            while (reader.Read())
                emp = new Employee();
                emp.DepartmentNmae = reader["projectName"].ToString();
            return emp;
Updated 7-Dec-18 3:23am

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Your query will return one or more rows with a single string column that has an auto-generated name:
Format Query Results as JSON with FOR JSON (SQL Server) | Microsoft Docs[^]
Use FOR JSON output in SQL Server and in client apps (SQL Server) | Microsoft Docs[^]

using (var myConnection = new SqlConnection("...")
using (var sqlCmd = new SqlCommand("select projectName from QryProjectWithDepartmentDetails ORDER BY projectName DESC FOR JSON PATH, WITHOUT_ARRAY_WRAPPER", myConnection))
    var sb = new System.Text.StringBuilder();
    using (var reader = sqlCmd.ExecuteReader())
        while (reader.Read())
    return new Employee { DepartmentName = sb.ToString() };

NB: You should avoid hard-coding your connection strings. Read them from the config file instead:
How to: Read Connection Strings from the Web.config File | Microsoft Docs[^]

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Cookies | Terms of Service
Web01 | 2.8.190214.1 | Last Updated 7 Dec 2018
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100