我想转换以下sql server查询与Linq-to-sql查询。我该怎么办怎么会这样?我正在使用c#。
SELECT Table1.CRNo, Table2.StageId
FROM Table1 INNER JOIN Table2
ON Table1.CRNo = Table2.CRNo
WHERE (Table2.IsActive = 'true')
表1和表2是两个表。两个表中的CRNo相同。表2是表1的详细表。
查询应该是什么。
被修改:
from record1 in table1
join record2 in table2 on record1.CRNo equals record2.CRNo
where record2.IsActive
select new { record1.CRNo, record2.StageId }
肯定,它工作正常。但是如果表2中有多个条目,结果还会带有IsActive False的记录。假设表2的记录为:
CRNo:1 StageId: 1 IsActive:False
CRNo:2 StageId: 1 IsActive:False
CRNo:1 StageId: 2 IsActive:True
然后CRNo 1会出现第1阶段,其中IsActive为False。为什么要这样呢? 请再次查看
答案 0 :(得分:3)
from record1 in table1
join record2 in table2 on record1.CRNo equals record2.CRNo
where record2.IsActive
select new { record1.CRNo, record2.StageId }
答案 1 :(得分:0)
如果表中的数据库中存在外键关系 - 或者在dbml中建模 - 您还可以执行以下操作:
from t1 in Table1
where t1.Table2.IsActive == "true" // assuming that IsActive is a string and not a boolean
select new { t1.CRNo, t1.Table2.StageId }
为了加快速度,您可以使用DataLoadOptions
指定每个t1
Table2
条目也应该被提取:
using (ctx = new MyDataContext()) {
var options = new DataLoadOptions();
options.LoadWith<Table1>(x => x.Table2);
ctx.LoadOptions = options;
var res = from t1 in Table1
where t1.Table2.IsActive == "true"
select new { t1.CRNo, t1.Table2.StageId };
}
此外,您可能希望look here获取linq语法的样本。
编辑 - 仅考虑有效条目:
from t1 in table1
join t2 in table2.Where(x => x.IsActive == "true") on t1.CRNo equals t2.CRNo
select new { t1.CRNo, t2.StageNo };