Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ: Get Table details

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?

like image 245
inquisitive_one Avatar asked Oct 05 '11 19:10

inquisitive_one


2 Answers

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.

like image 169
StriplingWarrior Avatar answered Oct 25 '22 08:10

StriplingWarrior


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.

like image 37
Joe Mancuso Avatar answered Oct 25 '22 08:10

Joe Mancuso