LINQ从动态tableName字符串中选择 [英] LINQ Select from dynamic tableName string
问题描述
我想从一个实体模型(我使用EF版本5)获取一个特定accountID的记录列表。我被提供了tableName字符串(这必须是动态的)和accountID。我正在尝试以下2种方法,但没有一个是工作的(给我的错误在IQueryable对象'表':
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>();
推荐答案
var query = table.Where(....) (...)
是正确的移动,并允许在运行时反映像查询构建器。
The var query = table.Where(....).Select(...)
is correct move, and that allows reflection like query builder in runtime.
但是, t .AccountID
是一个错误,因为 t
的类型仍然未知。
However, t.AccountID
is an error because of the type of t
remain unknown.
我已经做了很多年前类似的你唱 System.Linq.Expressions .Expression 直接在Linq2Sql中。
I have done many years ago similar by using System.Linq.Expressions.Expression directly in Linq2Sql.
eg
// 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>();
我记得应该是一个更简单的语法,如果你的对象有共同的界面
I remember that should a easier syntax, if you object has common interface
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;
或者,如果您只有几个表格来支持。
Or, if you only have a few table to support.
IQueryable<MyInterface> table;
if("table1"==tableName)
table=_db.table1
elseif("table2"==tableName)
table=_db.table2
elseif("table3"==tableName)
table=_db.table3
else
throw exception
这篇关于LINQ从动态tableName字符串中选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!