MNIK
MNIK

Reputation: 1619

EF - Execute a sql query/stored procedure that has dynamically generated fields

I'm using EF code first approach in my application. I need to execute a query which runs a report and returns the result set with dynamically generated fields. The fields in the result set can be different based on the condition. Is it possible to return a result set using code first approach like maybe in a DataSet, or is there any other way to achieve this?

Thanks.

Upvotes: 1

Views: 2580

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364259

(Untested) You can try to define data type which will have properties for all possible columns your query can return. It must be flat type with no nested objects and properties must have same names as columns in result set. Then you can use

var data = context.Database.SqlQuery<YourType>("Your SQL Query or SP call");

If you want DataSet with only returned columns you must use standard ADO.NET SqlDataAdapter or SqlConnection / SqlCommand (or version related to your database). EF doesn't like native queries which don't return fixed set of columns.

Upvotes: 2

Related Questions