LINQ 从动态 tableName 字符串中选择 [英] LINQ Select from dynamic tableName string
问题描述
我想从具有特定 accountID 的实体模型(我使用的是 EF 版本 5)获取记录列表.我得到了 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(....).Select(...)
是正确的做法允许在运行时对查询构建器进行反射.但是,t.AccountID
是一个错误,因为 t
的类型仍然未知.
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.
我以前在 LINQ to SQL 中使用过类似的方法,使用 System.Linq.Expressions.Expression,例如:
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
这篇关于LINQ 从动态 tableName 字符串中选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!