9
votes

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

2
Have you heard about Dynamic data framework, it may help you. - mipe34
LINQ is not a good fit for that. Consider using raw DataReaders, micro-ORMs, or DataTable. - SLaks
@SLaks is right. I have had a similiar situation and I build the SQL on the fly and use a micro-orm (ServiceStack.OrmLite to be precise) to return the data. - Moo-Juice
If you only have the table name as a string there's no real way to get a return value that's strongly typed. Since you don't know the type at compile time, even if you could implement such a method, you could never call it unless you knew, at compile time, what it's return type would be. Either it needs to return a non-statically typed result (i.e. DataTable) or you need to use generics such that the caller knows the return type at compile time. - Servy
Because the criteria isn't dynamic, I think you should go by looking up the tablename in the schema's (.GetTableNames() or something. What about return List<TableNAme>? Didn't u meant List<DataRow> or something? - Jeroen van Langen

2 Answers

3
votes

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);
2
votes

You could use entity framework and do this:

dynamiclist = this.datacontext.Set<T>().ToList(); // where T is the Type, represents the table in EF