我是linq的首发,我已经编写了这个T-SQL查询
select * from DOCUMENT_TYPES where document_id in(
select document_id from Clearance_Document where Clearance_id=(select clearance_id from clearance_id from request where request_id=3))
我想将此T-SQL查询转换为linq,请帮助我,谢谢
答案 0 :(得分:3)
好吧,我首先要将SQL重构为嵌套子查询链之外的其他内容。我认为这应该做同样的事情,而且它更具可读性:
SELECT
*
FROM
DOCUMENT_TYPES dt
JOIN
Clearance_Document cd
ON
dt.document_id = cd.document_id
JOIN
Request r
ON
cd.clearance_id = r.clearance_id
WHERE
r.request_id = 3
(我假设from clearance_id from request
是一个错字。)
然后您可以轻松地重构为LINQ语句:
var result = from dt in DOCUMENT_TYPES
join cd in Clearance_Document on dt.document_id equals cd.document_id
join r in Request on cd.clearance_id equals r.clearance_id
where r.request_id = 3
select new {
property1 = dt.something,
property2 = cd.somethingElse,
...
};
答案 1 :(得分:1)
var result =
from a in DOCUMENT_TYPES
let list =
(
from b in Clearance_Document
where b.Clearance_id == (from c in clearance_id where request_id == 3).First<string>())
select b
).ToList()
where list.Contains(a.document_id)
select a;
答案 2 :(得分:1)
应该做的事情(我猜你正在使用EF,但你可以很容易地适应其他LinQ类型):
context.Document_Types.Where(doc =>
conext.Clearance_Document.Where(cd =>
cd.Clearance_Id == context.Request.Single(r => r.Request_Id == 3)
).Contains(doc.Document_Id)
).ToList();
答案 3 :(得分:1)
怎么样
var result = c.Id context.Request.Single(r => r.Id == 3)
.Clearances.SelectMany(c => x.DocumentTypes);
实际上,获取Request
Id
且3
等于DocumentTypes
,然后获取所有Clearances
的所有{{1}}。< / p>
如果您的数据库设置了适当的外键,这些关系将自动生成为模型的一部分。