Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get table-data from table-name in LINQ DataContext

I need to get table data from table name from Linq DataContext.

Instead of this

var results = db.Authors;

I need to do something like this.

string tableName = "Authors";

var results = db[tableName];

It could be any table name that is available in DataContext.

like image 609
Krunal Avatar asked Dec 17 '09 05:12

Krunal


2 Answers

Given DataContext context and string tableName, you can just say:

var table = (ITable)context.GetType()
                           .GetProperty(tableName)
                           .GetValue(context, null);
like image 119
jason Avatar answered Sep 19 '22 13:09

jason


I am not sure if passing strings is an elegant solution. I would rather send the Type of entity as an argument to a method. Something on these lines :

var table = _dataCont.GetTable(typeof(Customer));

Here is the MSDN documentation.

like image 24
Perpetualcoder Avatar answered Sep 19 '22 13:09

Perpetualcoder