Krunal
Krunal

Reputation: 3541

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.

Upvotes: 15

Views: 36821

Answers (4)

DharmaTurtle
DharmaTurtle

Reputation: 8357

If you know the type, you can cast it. From http://social.msdn.microsoft.com/Forums/en-US/f5e5f3c8-ac3a-49c7-8dd2-e248c8736ffd/using-variable-table-name-in-linq-syntax?forum=linqprojectgeneral

MyDataContext db = new MyDataContext();
Assembly assembly = Assembly.GetExecutingAssembly();
Type t = assembly.GetType("Namespace." + strTableName);
if (t != null)
{
    var foos = db.GetTable(t);

    foreach (var f in foos)
    {
        PropertyInfo pi = f.GetType().GetProperty("Foo");
        int value = (int)pi.GetValue(f, null);
        Console.WriteLine(value);
    }
}

Upvotes: 0

jason
jason

Reputation: 241583

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

var table = (ITable)context.GetType()
                           .GetProperty(tableName)
                           .GetValue(context, null);

Upvotes: 16

Terje
Terje

Reputation: 1763

I am not sure I'd suggest it as a GOOD solution, but if you really need it, you could do something like this:

MyDBContext db = new MyDBContext();
Type t = db.GetType();
PropertyInfo p = t.GetProperty("Authors");
var table = p.GetValue(db, null);

That will give you the Authors table, as pr. Table.

Upvotes: 3

Perpetualcoder
Perpetualcoder

Reputation: 13571

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.

Upvotes: 4

Related Questions