Get All the Tables Name using LINQ

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

3 responses to “Get All the Tables Name using LINQ”

  1. […] Before going through this post, I recommend you to read Get All the Tables Name using LINQ […]

  2. 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?

  3. this is not support in .Net core using this namespace using System.Data.Linq.Mapping.

    Q: I want to get table name and i am passsing data as a parameter and from those parameter i want get table name so can i get please help

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 )

Facebook photo

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

Connecting to %s

Create a website or blog at WordPress.com