How can I create a LINQ-to-SQL statement when I have table name as string?

c#, linq, linq-to-sql

Solution

If you want the recordset, you can access the `Connection` property of the `DataContext` class (`db` variable in your context) and use it to execute regular query and get the result in either of `DataTable` or `DataReader`.

Problem

If I have the name of a database table like this: ``` string tableName = "Addresses"; string tableName = "Customers"; ``` How can I construct a dynamic LINQ statement like this: ``` var items = from o in db.{tableName} select o; foreach (var item in items) { sb.Append(item.Id + Environment.NewLine); } ``` I know I could do something like this: ``` IEnumerable<Customer> results = db.ExecuteQuery<Customer> ("SELECT contactname FROM customers WHERE city = {0}", "London"); ``` But in this instance I don't want strongly typed objects as my result, I just want a recordset to pick apart. Answer: Thanks Shalkalpesh, I took your advice and solved this by just avoiding LINQ altogether: ``` SqlConnection conn = new SqlConnection(); conn.ConnectionString = ConfigurationManager.ConnectionStrings["main"].ToString(); conn.Open(); string sql = "SELECT * FROM " + tableName; SqlDataAdapter da = new SqlDataAdapter(sql, conn); DataTable dtResult = new DataTable(); da.Fill(dtResult); foreach (DataRow drRow in dtResult.Rows) { Console.WriteLine(drRow["Id"].ToString()); } da.Dispose(); conn.Close(); conn.Dispose(); ```

Original source