Linq to SQL - Dynamic Table Name

I am using Linq to SQL, including Dynamic Linq queries. The example from documentation gives examples of retrieving dynamic columns using dynamic conditions, but not from a dynamic table itself. I do not know the table name my user wants until run time.

If I add "DataContext1.MyTable" to the watch, it shows "{Table(MyTable)}"

I get the same from the below using Reflections...
object table = DataContext1.GetType().GetProperty("MyTable").GetValue(DataContext1, null);

Which is good... but I am unable to use it for further querying.

Please help with the above or suggest your own solution for retrieving rows from a table mentioned during run time. I know both the table name and the list of all columns during run time.

I know I can simply resort to using SQL, but want to know if there is a Linq based solution.
Shahid ThaikaSole ProprietorAsked:
Who is Participating?
Hi, can't you just cast that table (object) to yours MyTable.

MyTable table = (MyTable)DataContext1.GetType().GetProperty("MyTable").GetValue(DataContext1, null);

Shahid ThaikaSole ProprietorAuthor Commented:
Wow!! I actually missed one of the four links that were posted during my own google search, and that had to be the one with the solution!!! Need to up my google skills a bit.

This was the solution that worked for me...

Type someEntity = Type.GetType("Namespace.EntityClassName");
IQueryable q = dc.GetTable(someEntity);

foreach (var someVariable in q)


So my code now looks like the one below...

Problem is how do I get the individual values out of the variable in the foreach loop? If I do something like "row. ", then it only gives four options... including .GetType(), .ToString(). If I add to the watch, I can see it is an object of my Table's Class type with all the columns and data, but I can't cast it, since I don't know the table's name until runtime.

NOTE: I have already found a solution for that as well, but I am keeping this open to see if any of you can come up with a better one.
string strTableName = "MyTable";
string columnName = "Field1";
Type tType = Type.GetType("MyProject." + strTableName);
IQueryable q = dc.GetTable(tType);

foreach (var someVariable in q)
    //How to get the column data out of the row?
    //Column names are known during runtime

Open in new window

Shahid ThaikaSole ProprietorAuthor Commented:
Part of me closing my old topics. A link lead me to some direction, but not the solution I was looking for. I ended up using a different approach for solving my task
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.