Reader Level:
ARTICLE

Listing columns name with type of a table using LINQ

Posted by Dhananjay Kumar Articles | LINQ December 29, 2010
After my last article, I got a question asking how to list all the Column names of a given table using LINQ.
  • 0
  • 0
  • 14335


After my last article, I got a question asking how to list all the Column names of a given table using LINQ.

Before going through this post, I recommend that you to read Get All the Tables Name using LINQ.

Let us say, you have a table called dbo.Person and you need to find all the columns of this particular table.

So first we need to find whether the table exists in DataContext or not

get1.gif

Dbo.Person is the name of the table.

We are looking through all the tables and finding whether a given table exists or not. Once we find the table we need to list all the column names.

get2.gif

Full source code is as below. In the code below we are determining whether the dbo.Person table exists or not. If it exists in DataContext then list all the column names.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq.Mapping;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {

            DataClasses1DataContext context = new DataClasses1DataContext();
            var datamodel = context.Mapping; 
 
            foreach (var r in datamodel.GetTables())
            {

                if (r.TableName.Equals("dbo.Person"StringComparison.InvariantCultureIgnoreCase))
                {
                     foreach (var r1 in r.RowType.DataMembers)
                    {
                        Console.WriteLine(r1.MappedName);
                    }
                }
                
            }
            Console.ReadKey(true);
        }

    }

}

Output

get3.gif

COMMENT USING