2

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>();

Chris Attard
  • 31
  • 1
  • 1
  • 5

2 Answers2

8

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
plr108
  • 1,201
  • 11
  • 16
Dennis C
  • 24,511
  • 12
  • 71
  • 99
0

I built a DynamicRepository for a project I am working on. It uses generic methods exposed through EF along with dynamic linq. It might be helpful to look at that source code here:

https://dynamicmvc.codeplex.com/SourceControl/latest#DynamicMVC/DynamicMVC/Data/DynamicRepository.cs

You can query the entity framework metadata workspace to get the type for a given table name. This link might help: Get Tables and Relationships

Community
  • 1
  • 1
Chris Perry
  • 121
  • 5