How to create a dynamic select query in C# using Entity Framework which will fetch all the column names from a SQL database. Here, the table names to be supplied in the query are fetched from a generic list of type IEnumerable<string>
There's a list mylist
where index [0] has the table name Store
, at index [1] there is a table Address
and at [2] there is a table Country
. Now, the query needs to be fired to database to find out what all column names are there are for Store
, Address
and Country
table.
I assume, the final query should be put in the below manner--
select
mylist[0].1stcolumnname,
mylist[0].2ndcolumnname,
.....,
mylist[1].1stcolumnname,
mylist[1].2ndcolumnname, ....,
mylist[2].1stcolumnname,
mylist[2].2ndcolumnname,
....
from
SOMETABLENAME WITH JOINS"
If these results are fetched correctly, then final output query to be fired would look something like
Select
"Store.id", "Store.Name", "Store.gstno", "Store.addressId",
"Address.addressId", "Address.addressLine1", "Address.addressLine2",
"Address.postcode", "Address.countryId",
"Country.countryId", "Country.name"
from
SOMETABLENAME WITH JOINS;
As you can see here, each table name with each column name is fetched and the query is created.
use this one:
using (var db = new EFDemoContext())
{
var columnNames = db.Database.SqlQuery<string>(" SELECT T.name + '.' + C.name AS Name
FROM sys.objects AS T
JOIN sys.columns AS C ON T.object_id = C.object_id
JOIN sys.types AS P ON C.system_type_id = P.system_type_id
WHERE T.type_desc = 'USER_TABLE' and T.name not like N'%sysdiagrams%';").ToList();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.