LINQ: Get Table Column Names

后端 未结 11 636
-上瘾入骨i
-上瘾入骨i 2020-12-31 01:14

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

相关标签:
11条回答
  • 2020-12-31 01:28

    In LinqPad:

    TableNames.Take(1) works.

    It is fast to type. (Although you in an ideal world, it would be nicer to not select any rows.)

    Note it is the pluralized form of TableName. You can also do Take(0) and look at the SQL results tab.

    0 讨论(0)
  • 2020-12-31 01:29

    I used this code in LinqPad

    from t in typeof(table_name).GetFields() select t.Name
    
    0 讨论(0)
  • 2020-12-31 01:33

    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.

    0 讨论(0)
  • 2020-12-31 01:35

    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?

    0 讨论(0)
  • 2020-12-31 01:37

    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.

    0 讨论(0)
  • 2020-12-31 01:37

    Iterate the properties of your L2S classes with reflection

    0 讨论(0)
提交回复
热议问题