LINQ Select from dynamic tableName string

混江龙づ霸主 提交于 2019-12-17 09:58:19

问题


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


回答1:


The var query = table.Where(....).Select(...) is correct move, and that allows reflection like query builder in runtime.

However, t.AccountID is an error because of the type of t remain unknown.

I have done many years ago similar by using System.Linq.Expressions.Expression directly in Linq2Sql.

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

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



回答2:


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



来源:https://stackoverflow.com/questions/25859143/linq-select-from-dynamic-tablename-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!