Friday, November 13, 2009

Get Tables and Columns Names by LINQ

Here I am explaining one of the tricks to get all table name list along with column of it from your DataContext.
I am using the System.Data.Linq.Mapping.MetaModel to get information about tables and it have much more database related information.

Following are the code to list all table name along with column from your DataContext.

//DataContext object.
DataClassesDataContext DB = new DataClassesDataContext();
//String variable to stor html to render.
string strHtmlToLoad = "";
strHtmlToLoad = "<-h2->Table Names<-/h2-><-ol->";
//Loop through tables add name to string
foreach (var mTable in DB.Mapping.GetTables())
strHtmlToLoad += "<-li->" + mTable.TableName + "<-ul->";

//Loop through table's columns add name to string
foreach (var mColumn in mTable.RowType.DataMembers)
strHtmlToLoad += "<-li->" + mColumn.MappedName + "<-/li->";
strHtmlToLoad += "<-/ul-><-/li->";

//Reander HTML
Response.Write(strHtmlToLoad + "<-/ol->");

Please remove "-" from above code. I have to add it because of HTML rendring of this post made that element active and mesh up the post formate.