我正在编写这样的查询:
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
的输入。
这可能吗?
答案 0 :(得分: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)
};
答案 1 :(得分: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
因此,请尝试使用Anonymous类型而不是SomeModel();