How to create a fully dynamic Linq query?

advertisements

I need to build about 30 different administration pages to add/edit/delete records from 30 different tables. I could obviously spend the time creating 30 unique pages, to query each table, but I'm curious if there's a way to simply create a single, dynamic page that queries a single, dynamic linq query. This linq query then returns all fields & records from a specified table.

I've seen examples of dynamic linq similar to this one (http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx), but that still requires hardcoding the table name into the query. I'd like to do a select all similar to this, where I pass in the name of the table (i.e. "Products", "Orders", etc), and then somehow query that table:

private List<tableName> MyDynamicQuery(string tableName)
 {
      IEnumerable<tableName> dynamicList;

      using (MyEntities db = _conn.GetContext())
      {
           dynamicList = (from q in db.<tableName>
                        select q).ToList();
      }
      return dynamicList;
 }

Is something like this even possible to do?

Thanks


Instead of using table names, why don't you pass in a selector? It would look something like this:

private List<T> GetData<T>(Func<MyEntities, IEnumerable<T>> selector)
{
    using (MyEntities db = _conn.GetContext())
    {
        return selector(db).ToList();
    }
}

You'd use it like so:

var orders = GetData(db => db.Orders);