C# 对另一个子查询使用查询内集合
我正在写这样一个查询:C# 对另一个子查询使用查询内集合,c#,linq-to-sql,C#,Linq To Sql,我正在写这样一个查询: var TheQuery = (from t in MyDC.Table1 where .... select new SomeContainerModel() { Collection1 = (from t2 in MyDC.Table2 ....
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
的输入
这可能吗?您可以使用
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)
};
问题是Collection1与Collection2不兼容。您已将Collection1转换为模型,无法再转换为SQL 我建议您将您的查询视为可解决的问题。直到最后,当您需要实际执行它并检索数据时 将每个查询想象为Transact-SQL脚本,即使将其与MyDC.Table3连接,实际上也只是添加一个子查询,类似于:
SELECT *
FROM Table3 a,
FROM (SELECT * FROM Table2 WHERE....) as SubQuery
WHERE a.SomeID == SubQuery.SomeOtherID
因此,尝试使用匿名类型而不是SomeModel()