LINQ从动态tableName字符串中选择

Chr*_*ard 3 linq select dynamic tablename

我想从实体模型(我使用EF版本5)获取具有特定accountID的记录列表.我正在提供tableName字符串(这必须是动态的)和accountID.我正在尝试以下两种方法,但它们都没有工作(给我IQueryable对象'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>();
Run Code Online (Sandbox Code Playgroud)

Den*_*s C 8

var query = table.Where(....).Select(...)是正确的移动,并允许在运行时像查询构建器一样进行反射.

但是,t.AccountID由于类型t仍然未知,是一个错误.

我在很多年前通过在Linq2Sql中直接使用System.Linq.Expressions.Expression来做类似的事情.

例如

// 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>();
Run Code Online (Sandbox Code Playgroud)

我记得如果你的对象有一个通用的接口应该是一个更简单的语法

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;
Run Code Online (Sandbox Code Playgroud)

或者,如果您只有几张桌子可以支持.

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