We need to list all the table name of the DataContext.
This is very simple through LINQ mapping.
1. Add the namespace
2. Get the model from type of datacontext
DataClasses1DataContext is your datacontext class created by LINQ to SQL.
3. Use GetTables() method to list all the tables name
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
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
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
3 responses to “Get All the Tables Name using LINQ”
[…] Before going through this post, I recommend you to read Get All the Tables Name using LINQ […]
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?
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