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

Discover more from Dhananjay Kumar

Subscribe to get the latest posts sent to your email.

Published by Dhananjay Kumar

Dhananjay Kumar is founder of NomadCoder and ng-India

3 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?

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

Discover more from Dhananjay Kumar

Subscribe now to keep reading and get access to the full archive.

Continue reading