Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
like image 227
Edward Tanguay Avatar asked Jan 29 '26 03:01

Edward Tanguay


1 Answers

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.

like image 99
shahkalpesh Avatar answered Jan 31 '26 16:01

shahkalpesh