How to return dynamic object from SQL query

后端 未结 3 2055
猫巷女王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:51

    You can't use SqlQuery 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> items = new List>();
        var reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            var item = new List();
            items.Add(item);
    
            for (int i = 0; i < reader.FieldCount ; i++)
                item.Add(reader[i]);
        }
    
        return Request.CreateResponse>(HttpStatusCode.OK, items);
    }
    
        

    提交回复
    热议问题