tags:

views:

142

answers:

2
+1  Q: 

TableName in Linq

hi

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?

+1  A: 

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.

tvanfosson
how can I get the columnlist from this IQueryable table in a foreach thanks :s
Cem
Use reflection to look for the properties on the type of the IQueryable object that have a ColumnAttribute, then you can get the property name from each of those properties and construct a list. The column attribute will also have information on the actual database column that it maps to.
tvanfosson
A: 

i got the idea, thanks, very helpful, however i couldnt be able to see those properties.

    string linqObjectName = "Test";
    PropertyInfo info = db.GetType().GetProperty(linqObjectName);
    IQueryable table = info.GetValue(db, null) as IQueryable;


    PropertyInfo[] properties = table.GetType().GetProperties();



    ltr.Text += "properties: <hr size=1/>";
    foreach (PropertyInfo p in properties)
    {
        ltr.Text += p.Name + "<br />";

    }

and thats the result;

properties:

Context IsReadOnly

Edit: I found it!

PropertyInfo[] properties = 
        table.Where("WebRef = \"" + webref + "\"").ElementType.GetProperties();
Cem