0

我有这 3 张桌子:

  1. FeatureTbl (FeatureId (PK),FeatureName)
  2. ParameterTbl (ParameterId (PK),ParameterName)
  3. Map_Parameter_To_Feature (MapId (PK),FeatureId(FK),ParameterId(FK))

我想将以下 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?

4

1 回答 1

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 }
于 2013-03-20T21:31:08.317 回答