LINQ: Get Table details

2019-06-16 07:23发布

问题:

I'm using LINQPad and I would like to know schema details of a table.

I know that I do it using SQL:

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

How can I do this using LINQ?

回答1:

LINQ to SQL contexts have a Mapping property that you can use for this sort of thing. A query like the one you provided might look something like this:

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}

See this answer for more details.



回答2:

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

'fields' will contain the names and types of the columns.



回答3:

In LINQ to SQL, you could try to bring in these views into the model. If that does not work, you could create a stored procedure that retrieves the info, then LINQ to SQL maps the stored procedure and you execute it as a function.