LINQ:获取表的详细信息

本文关键字:详细信息 获取 LINQ | 更新日期: 2023-09-27 18:10:27

我正在使用LINQPad,我想知道表的模式细节。

我知道我使用SQL:

SELECT column_name,* 
FROM information_schema.columns
WHERE table_name = '{table_name}'
ORDER BY ordinal_position

我如何使用LINQ来做到这一点?

LINQ:获取表的详细信息

LINQ to SQL上下文有一个Mapping属性,您可以将其用于此类事情。您提供的查询可能看起来像这样:

from t in context.Mapping.GetTables()
where t.TableName == "[table_name]"
from c in t.RowType.DataMembers
orderby c.Ordinal
select new {columnName = c.Name, columnInfo = c}

MetaTable t = MyDataContext.Mapping.GetTables().Where(
   i => i.TableName == "TABLENAME").SingleOrDefault();
PropertyInfo[] fields = t.RowType.InheritanceRoot.GetType().GetProperties();

'fields'将包含列的名称和类型。

在LINQ to SQL中,您可以尝试将这些视图引入模型。如果这不起作用,您可以创建一个检索信息的存储过程,然后LINQ to SQL映射存储过程,并将其作为函数执行。