1

In a code first approach I would like

static void Main()
{
    var sprocName = "sprocTesting";
    var db = new EntityContext();
    var result = db.Database.SqlQuery<object>(sprocName).ToList();
    var json = JsonConvert.SerializeObject(result);
}

In this particular case, I will not be able to have a class to return this into, the best I can do is Object.

This runs, but the output of result is nothing more than a list of {object}. The serialized json is nothing more than a bunch of empty braces

[{},{},{}....{}]

The count does match what I would expect from this stored procedure (5,228 results).

Is what I'm looking to do even doable or am I just missing something?

I should mention that if I do create a class to dump this into, then it works fine. But this is just one example where the stored procedure name will be passed in from another table, so I won't be able to build out a class for every possible result set, hence the need for the generics.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
gilliduck
  • 2,762
  • 2
  • 16
  • 32
  • It is not possible. You need a class for serialization to work and you need a class for the ORM to map the returned query values to. If you want dynamic you will have to write custom code to figure out the returned result set structure, read it in, and then determine how to serialize the result set to json. – Igor Feb 15 '18 at 17:37
  • @Igor Make that an answer, I'll accept it. – gilliduck Feb 16 '18 at 19:56

2 Answers2

0

It is not possible. You need a class for serialization to work and you need a class for the ORM to map the returned query values to.

If you want to do this without a concrete class definition you will have to write custom code to figure out the returned result set structure, read the result set in to memory, and then determine how to serialize that in memory result set to json.

Igor
  • 60,821
  • 10
  • 100
  • 175
0

Which version of SQL are you using?

You can use the for JSON path clause to do this easily if you have SQL 2016;

https://learn.microsoft.com/en-us/sql/relational-databases/json/format-query-results-as-json-with-for-json-sql-server

Milney
  • 6,253
  • 2
  • 19
  • 33