C# LINQ:获取表列名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1803192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
LINQ: Get Table Column Names
提问by Lennie De Villiers
Using LINQ, how can I get the column names of a table? C# 3.0, 3.5 framework
使用 LINQ,如何获取表的列名?C# 3.0、3.5 框架
采纳答案by RichardOD
I assume you mean by using LINQ to SQL, in which case look at the DataContext.Mappingproperty. That's what I use.
我假设您的意思是使用 LINQ to SQL,在这种情况下,请查看DataContext.Mapping属性。这就是我使用的。
If you don't mean that, perhaps you can elaborate on what you are trying to achieve?
如果您不是那个意思,也许您可以详细说明您要实现的目标?
回答by Matt Kocaj
Iterate the properties of your L2S classes with reflection
使用反射迭代 L2S 类的属性
回答by marc_s
Use the ExecuteQuery method on your data context and execute this SQL script:
在您的数据上下文中使用 ExecuteQuery 方法并执行此 SQL 脚本:
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.
这为您IEnumerable<string>
提供了您指定的表中的所有列名。
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.
当然,如果您愿意和需要,您始终可以从sys.columns
SQL Server的目录视图中检索更多信息(例如数据类型、最大长度)。
回答by Mike Two
If you are talking about getting the columns for a mapped table then see this answerto see how to get to the column attributes. From there you can get the column names, types, etc.
如果您正在谈论获取映射表的列,请参阅此答案以了解如何获取列属性。从那里你可以得到列名、类型等。
回答by Marty Neal
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.
我偶然发现了这个问题,正在寻找同样的东西,但在这里没有看到一个很好的答案。这就是我想出的。在 C# 表达式模式下直接扔到 LINQPad 中即可。
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.
根据您的需要进行修改。
回答by erkan
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;
回答by Don
I used this code in LinqPad
我在 LinqPad 中使用了这段代码
from t in typeof(table_name).GetFields() select t.Name
回答by ravi kumar
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
回答by William
var query = from x in DataBase.Table_Name
select x.Column_Name;
回答by Curtis Yallop
sp_help 'TableName'
sp_help '表名'
An option for a LinqPad SQL window to ms sql server
一个 LinqPad SQL 窗口到 ms sql server 的选项