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
Leave a Reply