我正在使用实体框架
所以我想用两个表写一个sql命令 - tblContractor和tbSiteByCont表。
在SQL
SELECT PKConID, Fname, Lname
FROM tblContractor
WHERE (PKConID NOT IN
(SELECT FKConID
FROM tbSiteByCont
WHERE (FKSiteID = 13)))
但我不知道如何用Linq写作。
我试过这个
var query1 = from s in db.tblSiteByConts
where s.FKSiteID == id
select s.FKConID;
var query = from c in db.tblContractors
where c.PKConID != query1.Any()
select Contractor;
但这不起作用。 那我该怎么写呢?程序是什么?我是Linq的新手。
答案 0 :(得分:18)
var _result = from a in tblContractor
where !(from b in tbSiteByCont
where FKSiteID == 13
select b.FKConID)
.Contains(a.PKConID)
select a;
或
var siteLst = tbSiteByCont.Where(y => y.FKSiteID == 13)
.Select(x => x.FKConID);
var _result = tblContractor.Where(x => !siteLst.Contains(x.PKConID));
答案 1 :(得分:4)
我使用HashSet,它确保你只评估一次序列。
var result = from p in tblContractor
let hasht = new HashSet<int>((from b in tbSiteByCont
where b.FKSiteID == 13
select b.PKConID).Distinct())
where !hasht.Contains(p.PKConID)
select p;
答案 2 :(得分:0)
这可能也有效
var _result = from a in tblContractor
.Where(c => tbSiteByCont
.Count(sbc => sbc.FKSiteID == 13 && c.PKConID == sbc.FKConID) == 0)