We need to list all the table name of the DataContext.
This is very simple through LINQ mapping.
1. Add the namespace
clip_image001
2. Get the model from type of datacontext
clip_image003
DataClasses1DataContext is your datacontext class created by LINQ to SQL.
3. Use GetTables() method to list all the tables name
clip_image004

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)
        {
            var datamodel = new AttributeMappingSource().GetModel(typeof(DataClasses1DataContext));
            foreach (var r in datamodel.GetTables())
            {
                Console.WriteLine(r.TableName);
            }
            Console.ReadKey(true);
        }
    }
}

Output
clip_image006
There is one more scenario. If you have already instance of DataContext and you want to list all the tables name then you need to get the model as below
clip_image007
Here context is instance of datacontext class.

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())
            {
                Console.WriteLine(r.TableName);
            }
            Console.ReadKey(true);
        }
    }
}

Output
clip_image009
Advertisements

2 thoughts on “Get All the Tables Name using LINQ

  1. Hi Dhananjay. thank you for this post. i was searching for this more than one week.

    my situation is like i need to pass table names and column names dynamically and need to query against those tables.

    one more case is like i have to pass diffrent view names dynamically , and need to process it one function.

    could you please help me?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s