inquisitive_one
inquisitive_one

Reputation: 1495

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?

Upvotes: 10

Views: 9047

Answers (3)

StriplingWarrior
StriplingWarrior

Reputation: 156459

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.

Upvotes: 7

Joe Mancuso
Joe Mancuso

Reputation: 2129

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.

Upvotes: 4

Brian Mains
Brian Mains

Reputation: 50728

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.

Upvotes: 0

Related Questions