LINQ: Get Table Column Names
45,764
Solution 1
I assume you mean by using LINQ to SQL, in which case look at the DataContext.Mapping property. That's what I use.
If you don't mean that, perhaps you can elaborate on what you are trying to achieve?
Solution 2
Maybe It is too late but, I solved this problem by this code
var db = new DataContex();
var columnNames = db.Mapping.MappingSource
.GetModel(typeof(DataContex))
.GetMetaType(typeof(_tablename))
.DataMembers;
Solution 3
The below code will worked from returns all the column names of the table
var columnnames = from t in typeof(table_name).GetProperties() select t.Name
Solution 4
I stumbled upon this question looking for the same thing and didn't see a really good answer here. This is what I came up with. Just throw it into LINQPad under C# expression mode.
from t in typeof(UserQuery).GetProperties()
where t.Name == "Customers"
from c in t.GetValue(this,null).GetType().GetGenericArguments()[0].GetFields()
select c.Name
Modify as you see fit.
Solution 5
I used this code in LinqPad
from t in typeof(table_name).GetFields() select t.Name
Author by
Lennie De Villiers
Updated on January 03, 2021Comments
-
Lennie De Villiers over 3 years
Using LINQ, how can I get the column names of a table? C# 3.0, 3.5 framework
-
Lennie De Villiers over 14 yearsI want to write a program using LINQPad (C#) That can build SQL insert statements off course for this I require the column names of the tables.
-
Morgan Herlocker about 13 yearscould this be clarified a bit...this is not much of an answer.
-
draconis over 11 yearsNot sure why this was not upvoted, it is the most elegant answer. Here is the lambda syntax equivalent: var columnnames = typeof(table_name).GetProperties().Select(t => t.Name);
-
Doctor Jones over 11 yearsSome example usage would be great. The Mapping API is a bit un-intuitive to say the least...
-
Doctor Jones over 11 yearsThanks, you just saved me a boat load of time. This is better than the accepted answer because this shows how to use the DataContext.Mapping property.
-
Zarepheth almost 11 yearsFor VB.Net use
GetType(DataContext)
instead oftypeof(DataContext)
. -
mbx over 10 yearsMaybe this wasn't upvoted as you don't only get the columns but additional properties as well. It's usually a partial class with extensibility in mind after all.
-
Curtis Yallop almost 10 yearsNote that it is the unpluralized version of the table name.
-
Gert Arnold over 3 yearsThis gives property names, not table column names. Also, the question is not about EF, already has many answers, and there are similar questions that are about EF.