Search code examples
linqselectdynamictablename

LINQ Select from dynamic tableName string


I want to get list of records from an entity model (I'm using EF version 5) with a particular accountID. I'm being supplied with the tableName string (this has to be dynamic) and the accountID. I'm trying the following 2 methods but none of them is working (giving me errors on the IQueryable object 'table':


PropertyInfo info = _db.GetType().GetProperty(tableName);
IQueryable table = info.GetValue(_db, null) as IQueryable;

var query = table.Where(t => t.AccountID == accID)
                        .Select(t => t);

List <object> recList = (   from records in table
                            where records.AccountID == accID
                            select records).ToList<object>();


Solution

  • The var query = table.Where(....).Select(...) is the correct move as it allows reflection for the query builder at runtime. However, t.AccountID is an error because of the type of t remains unknown.

    I've previously used a similar approach in LINQ to SQL, using System.Linq.Expressions.Expression, e.g.:

        // NOT TESTED
        var table=context.GetTable(dynamicTableName);
        var theT=table.Experssion; // actually, I forget. DynamicExpression  or MemberBinding? or
        var theField=Expression.Field(theT, "AccountID"); // or dynamic name
        var query=table.Where(Expression.Equal(theField, accID);
        var recList=query.ToList<object>();
    

    If your object has a common interface there is a simpler syntax:

    IQueryable<MyInterface> table = context.GetTable("table") as IQueryable<MyInterface>;
        var recList=from r in table
                    where table.AccountID == ac // if your AccountID is on MyInterface
                    select table;
    

    If you only have a few tables to support, you could do this as well:

        IQueryable<MyInterface> table;
        if("table1"==tableName)
           table=_db.table1
        elseif("table2"==tableName)
           table=_db.table2
        elseif("table3"==tableName)
           table=_db.table3
        else
           throw exception