ARTICLE

Get All the Tables Name using LINQ

Posted by Dhananjay Kumar Articles | LINQ December 28, 2010
In this article you will learn how to get the names of all the tables using LINQ
Reader Level:


We need to list the names of all the tables of the DataContext.

This is very simple using LINQ mapping.

1. Add the namespace

1.gif

2. Get the model of the datacontext type.

2.gif

DataClasses1DataContext is your datacontext class created by LINQ to SQL.

3. Use GetTables() method to list all the table names.

3.gif

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

4.gif

There is one more scenario. If you already have an instance of a DataContext and you want to list all the table names then you need to get the model as below:

5.gif

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

6.gif

erver'>
Login to add your contents and source code to this article
comments
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
Join a Chapter
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Get Career Advice from Experts