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

If I have a database table name as follows:

string tableName = "Addresses";
string tableName = "Customers";

How can I build a dynamic LINQ statement as follows:

var items = from o in db.{tableName}
            select o;

foreach (var item in items)
{
    sb.Append(item.Id + Environment.NewLine);
}

I know I can do something like this:

IEnumerable<Customer> results = db.ExecuteQuery<Customer>
    ("SELECT contactname FROM customers WHERE city = {0}",
    "London");

But in this case, I don’t want the objects with typed typing to be the result, I just want the recordset to be highlighted.

Answer:

Thanks to Shalkalpesh, I took your advice and solved this by simply avoiding LINQ at all :

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();
+3
source share
6 answers

, Connection DataContext (db ) DataTable DataReader.

+4

- dev-, this help?

, DynamicQuery...

- - DynamicQuery. DynamicQuery , 101 LINQ, "" | Visual Studio. DynamicQuery , , .

DynamicQuery - . , , .Where() (, , .Single() ). , Dynamic Query . Load() :

...

+1

LINQ to SQL , , LINQ to SQL , ExecuteQuery

0

, Dynamic Linq .

, .

linq - , , .

, , :

Product {Id, Name, Value}
Customer {Id, Firstname, Surname, Address, Email, ...}

Linq-to-SQL ORM:

var items = from p in MagicTableResolver("Product")
            where p.Firstname // <-- How could intellisense allow this?
            select p;

var items = from c in MagicTableResolver("Customer")
            where c.Name // <-- It can't, it cannot be strongly typed
            select c;
0

Creating this and this , here's how to run some LINQ commands on the tablename line. I did not understand how to make the query syntax work (for example, "FROM" and "SELECT"), but you can still get and insert rows.

Type tableType = Assembly.GetExecutingAssembly().GetType("NameSpace.TableName");
ITable itable = dbcontext.GetTable(tableType);

//prints contents of the table
foreach (object y in itable) {
    string value = (string)y.GetType().GetProperty("ColumnName").GetValue(y, null);
    Console.WriteLine(value);
}

//inserting into a table
dynamic tableClass = Activator.CreateInstance(tableType);
//Alternative to using tableType
dynamic tableClass = Activator.CreateInstance(null, "NameSpace.TableName").Unwrap();
tableClass.Word = userParameter;
itable.InsertOnSubmit(tableClass);
dbcontext.SubmitChanges();

//sql equivalent
dbcontext.ExecuteCommand("INSERT INTO [TableName]([ColumnName]) VALUES ({0})", userParameter);
0
source

Source: https://habr.com/ru/post/1724291/


All Articles