0

I have following function for reporting purposes. Basically, client wants to see last top 100 rows from specific tables. I tried to return List<dynamic> from SqlQuery function, and it returns with 100 objects. But the problem is when I serialize this list into JSON i get full list of empty objects.

public IList<object> GetTableContents(string tableName)
        {
            using (Context)
            {
                string query = string.Format("select top 100 * from {0} order by createDate desc",tableName);
                List<dynamic> objects = Context.Database.SqlQuery<dynamic>(query).ToList();
                return objects;
            }
        }

I am getting empty array below.

JsonConvert.SerializeObject(objects)

I know I can use ADO.NET data reader and read columns and rows dynamically, but I want to know is there any way to retrieve dynamic list from Entity Framework? Then I can bind it to a JSON GridView reader?

Teoman shipahi
  • 47,454
  • 15
  • 134
  • 158
  • 1
    Can you return and query using object rather than dynamic? – Brian Mains Aug 03 '15 at 02:44
  • are the tables the client needs arbitrary, or from a pre-determined list? If its pre-determined (and reasonable in number), why not use a switch-case for the specified table? Or as Brian suggests, use List instead of List – elliot-j Aug 03 '15 at 03:06
  • @BrianMains I am getting same empty list when I use object. (After I serialize) – Teoman shipahi Aug 03 '15 at 03:23
  • @sparticus_37 table list is not pre-determined. New tables can be added and client wants to see them dynamically. – Teoman shipahi Aug 03 '15 at 03:24

1 Answers1

0

If you are using the Database first approach, one possible option would be to use reflection to look up the Entity object from the context based on the table name instead of using a sql query on the context itself.

context.GetType().GetProperty(tableName).GetValue(context, null);

This would also be a bit safer from an error handling persepctive since you would get an exception for non-existant/invalid tables instead of having the db server telling you about an error.

See How to get a property value based on the name

Community
  • 1
  • 1
elliot-j
  • 10,709
  • 3
  • 19
  • 18