Get All the Tables Name using LINQ



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'>
Up Next
    Ebook Download
    View all
    Learn
    View all