2013-03-20 74 views
0

我有這3個表:如何做內部連接,並在同一查詢右外連接

  1. FeatureTbl(FEATUREID(PK),FeatureName)
  2. ParameterTbl(參數標識(PK)參數名稱)
  3. Map_Parameter_To_Feature(的azazaz(PK),FEATUREID(FK),參數標識(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?

+1

這可能會幫助:http://www.hookedonlinq.com/OuterJoinSample.ashx – xQbert 2013-03-20 21:31:02

回答

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 } 
+1

我「DbIsNullExpression的參數必須引用基元,枚舉或引用類型。」所以我改變我改變了最後的選擇,選擇新 { FEATUREID = f.FeatureId, FeatureName = f.FeatureName, PID =((空== p.ParameterId)-1:p.ParameterId), PNAME =((null == p.ParameterName)?「NA」:p.ParameterName) }); – shresthaal 2013-03-20 22:40:01