0

我正在尝试创建一个通用类,我可以在其中传递两个表并返回第一个表。这两个变量是我用来连接 linq 查询中的表的字符串值。我想要返回的是一个 IQueryable 值,但它一直返回一个 DataQuery 值。

这在我的 MVC 视图中失败并出现错误“方法'System.Reflection.PropertyInfo GetProperty(System.String)'没有支持的 SQL 转换”

下面的代码:

    var result = GetTable<Table1, Table2>("Table1id", "Table2id");


    public virtual IQueryable<T> GetTable<T, A>(string table1Variable,
                                        string table2Variable) 
                                                  where T : class
                                                  where A : class
    {
        var table1 = entityDatabaseDC.GetTable<T>();
        var table2 = entityDatabaseDC.GetTable<A>();

        return from entity in table1.AsQueryable()
               join entity2 in table2 on entity.GetType().GetProperty(table1Variable)
                                      equals  entity2.GetType().GetProperty(table2Variable)
               select entity;

    }

它适用于单个表:

     var result = repository.GetTable<Table1>();

     public virtual IQueryable<T> GetTable<T>() where T : class
    {
           return entityDatabaseDC.GetTable<T>();
    }

我想知道我正在尝试的是否可行。

4

3 回答 3

0

也许你应该尝试这样的事情:

   public virtual IQueryable<T> GetTable<T, A>(string table1Variable,
                                        string table2Variable) 
                                                  where T : class
                                                  where A : class
    {
        var table1 = entityDatabaseDC.GetTable<T>();
        var table2 = entityDatabaseDC.GetTable<A>();

        return from entity in table1.AsQueryable()
               join entity2 in table2 on 
               entity.GetType().GetProperty(table1Variable).GetValue(table1,null)
                                      equals 
               entity2.GetType().GetProperty(table2Variable).GetValue(table2,null)
               select entity;

    }

不是.GetValue(table1,null)在属性之后。

于 2013-02-19T18:48:04.960 回答
0

问题是 linq-to-sql 试图将连接表达式(嗯,整个语句)翻译成 SQL。当然,没有办法GetProperty从 SQL 语句中进行调用。

所以我担心这永远不会奏效。但也许你可以按照这里的建议来做:如何创建动态 LINQ 连接扩展方法

于 2013-02-19T21:26:06.983 回答
0

感谢您的输入。在对这个问题进行了更多研究之后,我决定退后一步,回到绘图板上思考这是否是我想要实现的正确解决方案以及它是否有益。

于 2013-03-06T10:52:55.110 回答