views:

628

answers:

6

Using LINQ, how can I get the column names of a table? C# 3.0, 3.5 framework

A: 

Iterate the properties of your L2S classes with reflection

cottsak
+3  A: 

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?

RichardOD
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.
Lennie De Villiers
A: 

Use the ExecuteQuery method on your data context and execute this SQL script:

var columnNames = ctx.ExecuteQuery<string>
    ("SELECT name FROM sys.columns WHERE object_id = OBJECT_ID('your table name');");

This gives you an IEnumerable<string> with all the column names in that table you specified.

Of course, if you want and need to, you could always retrieve more information (e.g. data type, max length) from the sys.columns catalog view in SQL Server.

marc_s
A: 

If you are talking about getting the columns for a mapped table then see this answer to see how to get to the column attributes. From there you can get the column names, types, etc.

Mike Two
A: 

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.

Martin Neal
A: 

Maybe It is too late but,I solved this problem by this code

var db=new DataContex(); var columnname=db.Mapping.MappingSource .GetModel(typeof(DataContex)) .GetMetaType(typeof(_tablename)) .DataMembers;

erkan