views:

314

answers:

5

Hi

I want to build dynamic linq.

But I want to dynamically set the table (from clause)

Is this possible?

Malcolm

A: 

I will have the table as a string???

Malcolm
+1  A: 

As always, it depends ;-p

If you want to use the LINQ extension methods or query syntax, then no: this is tightly coupled to IQueryable<T>, where T is the source type. Generics might be an option, depending on the scenario:

public IQueryable<T> Get<T>(int id) where T : SomeBaseClass
{
    return GetData<T>().Where(row=>row.SomeProp == id);
}

The above could be made to work with LINQ-to-SQL, for example, by using GetTable<T>() (and specially hand-crafted data objects). Of course, to get from a string to generics you'd have to use reflection (MakeGenericMethod) - so not trivial!

Can you clarify the exact scenario here?

It sounds like maybe you should just use a regular command here... for example, perhaps with ExecuteQuery, which takes a string command and loads the data into typed objects.

Marc Gravell
A: 

I think you are porsible comming fresh from the SQL world (guess), and then yes, the first thing you want to do is to build the query from strings (i wanted that too). But in Linq we really dont like string anyware, so if you someway can send the type of table to query, instead of the string name, then Linq will be happy, and you have compiler time checking of your query works. Its a win-win situation :)

So yes, give os some exsample of why you really want the table name as a string :)

Jesper Blad Jensen aka. Deldy
A: 

The app is a utility to allow a DBA or the like be able to generate sql test data. ie a table name and a row id and number of rows is provided to this program and it generates row copies.

So I wanted it to be able to generate any table in a DB.

Maybe ADO.NET would be best but I thought I would try LINQ

Malcolm
You should edit your question with additional details.
AnthonyWJones
A: 

LINK is not SQL.

Of course you can use it to get data out of a SQL Server database using LINQ-To-SQL, but LINQ and SQL are two very different things.

In a lot of cases their usage patterns look alike, but the advantage of LINQ is to have compile-time type checking and inferring instead of run-time checking. You can't have that with SQL.

Dave Van den Eynde