3

我想从具有特定 accountID 的实体模型(我使用的是 EF 版本 5)中获取记录列表。我得到了 tableName 字符串(这必须是动态的)和 accountID。我正在尝试以下 2 种方法,但它们都不起作用(在 IQueryable 对象“表”上出现错误:


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

4

2 回答 2

8

var query = table.Where(....).Select(...)是正确的举动,因为它允许查询构建器在运行时进行反射。但是,t.AccountID是一个错误,因为类型t仍然未知。

我以前在 LINQ to SQL 中使用过类似的方法,使用 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>();

如果您的对象有一个通用接口,则有一个更简单的语法:

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;

如果您只有几个表要支持,您也可以这样做:

    IQueryable<MyInterface> table;
    if("table1"==tableName)
       table=_db.table1
    elseif("table2"==tableName)
       table=_db.table2
    elseif("table3"==tableName)
       table=_db.table3
    else
       throw exception
于 2014-09-16T01:23:02.560 回答
0

我为我正在处理的项目构建了一个 DynamicRepository。它使用通过 EF 公开的通用方法以及动态 linq。在此处查看该源代码可能会有所帮助:

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

您可以查询实体框架元数据工作区以获取给定表名的类型。此链接可能会有所帮助: 获取表格和关系

于 2014-09-16T03:11:25.740 回答