0

我正在写这样的查询:

var TheQuery = (from t in MyDC.Table1
                where ....
                select new SomeContainerModel()
                {
                    Collection1 = (from t2 in MyDC.Table2
                                   ....
                                   select new SomeModel()
                                   {
                                       SomeID = t2.SomeID
                                   }

                     Collection2 = (from x in Collection1
                                    from t3 in MyDC.Table3
                                    where x.SomeID == t3.SomeOtherID

我想要做的是将 的结果Collection1用作Collection2.

那可能吗?

4

2 回答 2

2

您可以使用let关键字为子查询结果引入新的范围变量。

var theQuery = (from t in MyDC.Table1
                let subQuery = (from t2 in MyDC.Table2
                                ...
                                select new SomeModel() { SomeID = t2.SomeID })
                where ....                
                select new SomeContainerModel()
                {
                    Collection1 = subQuery,
                    Collection2 = (from x in subQuery
                                    from t3 in MyDC.Table3
                                    where x.SomeID == t3.SomeOtherID)
                };
于 2012-10-15T22:18:13.107 回答
0

问题是 Collection1 与 Collection2 不兼容。您将 Collection1 转换为模型,并且无法再转换为 SQL。

我建议您将查询视为 IQuerable。直到最后,当您需要物理执行它并检索数据时。

将每个查询想象为 Transact-SQL 脚本,即使您将其与 MyDC.Table3 连接起来,您实际上也只是添加了一个子查询,例如:

SELECT * 
FROM Table3 a,
FROM (SELECT * FROM Table2 WHERE....) as SubQuery 
WHERE a.SomeID == SubQuery.SomeOtherID

因此,请尝试使用匿名类型而不是 SomeModel();

于 2012-10-15T22:38:08.283 回答