How to return dynamic object from SQL query

后端 未结 3 2038
猫巷女王i
猫巷女王i 2020-12-21 14:16

I have situation where a storeprocdure return collection, but I do not how the object structure because the query is very dynamic.

One query can return:

相关标签:
3条回答
  • 2020-12-21 14:42

    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;}
    }
    
    0 讨论(0)
  • 2020-12-21 14:51

    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);
    }
    
    0 讨论(0)
  • 2020-12-21 15:05

    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)
    
    0 讨论(0)
提交回复
热议问题