.net – TableName in Linq

linqvb.net

My Sql Query in Vb.net is like this:

Dim TableName As String ="City"
Dim Str As String="Select * from "+TableName+""

I got TableName from another Form .how we can do this in linq?
can we use TableName in Linq query dynamically?

please help me?

Best Solution

Sorry for my example being in C#, but my Vb is rusty. I can read it, but not write it very well off the top of my head.

The best way I can think to do this is to use reflection and extension methods rather than LINQ syntax.

 PropertyInfo info = dataContext.GetType().GetProperty( "City" );
 IQueryable table = info.GetValue( dataContext, null ) as IQueryable;

 var query = table.Where( t => t.Column == "Value" )
                  .Select( t => t.OtherColumn );

I'm assuming LINQtoSQL in this example and so am getting the object from the datacontext. If you're using something else, you'll need to adjust the method of finding the object.

You could also use a stack of if-then statements based on the value of the table name. If the number of possible tables was fixed and small, this might be better.