我有这3张桌子:
我想将以下SQL转换为LINQ:
SELECT
FeatureTbl.FeatureId,
FeatureTbl.FeatureName,
Map_Parameter_To_Feature.ParameterId,
ParameterTbl.ParameterName
FROM ParameterTbl
INNER JOIN Map_Parameter_To_Feature
ON ParameterTbl.ParameterId = Map_Parameter_To_Feature.ParameterId
RIGHT OUTER JOIN FeatureTbl
ON Map_Parameter_To_Feature.FeatureId = FeatureTbl.FeatureId
以上查询返回以下结果
FeatureId,FeatureName,ParameterId,ParameterName
1 Feat A NULL NULL
2 Feat B 10 Param X
3 Feat B 10 Param Y
4 Feat C NULL NULL
我写了以下LINQ:
(from p in context.ParameterTbls
join mp2f in context.Map_Parameter_To_Feature
on p.ParameterId equals mp2f.ParameterId
join f in context.FeatureTbls
on mp2f.FeatureId equals f.FeatureId
into desiredresult
from r in desiredresult.DefaultIfEmpty()
select new {
r.FeatureId,
r.FeatureName,
mp2f.ParameterId,
p.ParameterName
});
但我得到了这个结果
FeatureId,FeatureName,ParameterId,ParameterName
2 Feat B 10 Param X
3 Feat B 10 Param Y
如何将上述SQL转换为LINQ?
答案 0 :(得分:1)
LINQ没有正确的连接运算符,但您可以将其重写为左连接:
from f in context.FeatureTbls
join mp in (
from p in context.ParameterTbls
join mp2f in context.Map_Parameter_To_Feature on p.ParameterId equals mp2f.ParameterId
select new { mp2f.FeatureId, p.ParameterId, p.ParameterName }
) on f.FeatureId equals mp.FeatureId into ps
from p in ps.DefaultIfEmpty()
select new { f.FeatureId, f.FeatureName, null == p.ParameterId ? (int?)null : p.ParameterId, null == p.ParameterName ? null : p.ParameterName }