How to get data dynamically from you LINQ to SQL data context

Lately I have been playing around with LINQ to SQL and let me tell you this. It is super cool! 😀 So today I wanted to check how I can grab data from all tables that are mapped in my LINQ to SQL mapping file. I discovered that it is really easy… In fact it is just a few lines of code. Have a look …

NWDataContext context = new NWDataContext();
var model = context.Mapping;
//get all tables 
foreach (var mt in model.GetTables())
    Console.WriteLine("Getting data " + mt.TableName);
    //generate a sql statment for each table - just grab the first 20
    string sql = String.Format("Select Top 20 * from {0} ", mt.TableName);
    var data = context.ExecuteQuery(mt.RowType.Type, sql);
    //data is here now. Lets print it on the console
    foreach (var item in data)

So all you need to do is to get the list of table meta from the data context and then generate a sql that grabs all the data from the specific table…

You can get loads of other information from the table meta for more details click here.

To get info about the DataMembers of a specific table you can use the RowType property of the TableMeta that you get from the GetTables().


kick it on