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
Share:
45,764
Lennie De Villiers
Author by

Lennie De Villiers

Updated on January 03, 2021

Comments

  • Lennie De Villiers
    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
    Lennie De Villiers over 14 years
    I 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
    Morgan Herlocker about 13 years
    could this be clarified a bit...this is not much of an answer.
  • draconis
    draconis over 11 years
    Not 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
    Doctor Jones over 11 years
    Some example usage would be great. The Mapping API is a bit un-intuitive to say the least...
  • Doctor Jones
    Doctor Jones over 11 years
    Thanks, 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
    Zarepheth almost 11 years
    For VB.Net use GetType(DataContext) instead of typeof(DataContext).
  • mbx
    mbx over 10 years
    Maybe 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
    Curtis Yallop almost 10 years
    Note that it is the unpluralized version of the table name.
  • Gert Arnold
    Gert Arnold over 3 years
    This 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.