How to return dynamic object from SQL query

六月ゝ 毕业季﹏ 提交于 2019-11-29 16:24:50

You can't use SqlQuery<T> for custom fields.

Creates a raw SQL query that will return elements of the given generic type. The type can be any type that has properties that match the names of the columns returned from the query, or can be a simple primitive type. - MSDN

But, you can use ExecuteReader to achieve that.

using (var db = new Context())
{
    db.Database.Connection.Open();

    var cmd = db.Database.Connection.CreateCommand();
    cmd.CommandText = "SP @Param1, @Param2";
    cmd.Parameters.Add(new SqlParameter("Param1", ped));
    cmd.Parameters.Add(new SqlParameter("Param2", 25));

    List<List<object>> items = new List<List<object>>();
    var reader = cmd.ExecuteReader();
    while (reader.Read())
    {
        var item = new List<Object>();
        items.Add(item);

        for (int i = 0; i < reader.FieldCount ; i++)
            item.Add(reader[i]);
    }

    return Request.CreateResponse<List<object>>(HttpStatusCode.OK, items);
}

If you know what all the possible columns could be returned, there is no issue with using a class that has more properties than you need.

public class Data
{
public int ID {get;set;}
public string SalesRep {get;set;}//Simply will be empty in the first example, but populated in the second.
public string Location {get;set;}
}

If on SQL 2016 or newer, add "FOR JSON AUTO" to your query to return as JSON, e.g:

var json = db.Database.SqlQuery<string>("Select x, y, z FROM tbl FOR JSON AUTO").First();

Then use Json.Net to create a dynamic object using

var myDynamic = JObject.Parse(json)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!