2013-02-11 28 views
0

我試圖複製在LINQ下面的SQL查詢:的LINQ和的EntityFramework,ISNULL和獲取單個值的加入

Select 
    l.*, 
    ISNULL(i.InterestPercentage,0) 
    as InterestPercentage 
FROM properties l 
LEFT JOIN interest i on i.ListingKey = l.ListingKey 
Where i.userId = {0} 

我真的沒有太多去的那一刻:

var results = from l in context.properties 
       join s in context.interest on l.ListingKey equals s.ListingKey 
       where s.userId == ""; 

這將返回我一個完整的加盟,但我想用一個單一的附加價值迴歸的屬性外,InterestPercentage。我想我可能需要創建一個新的對象,它是所有具有InterestPercentage屬性的屬性列。然後添加select new MyObject { tons of property setters }

此外,雖然,我試圖通過Odata公開這個,我會失去這個可查詢的能力嗎?

回答

2

你可以嘗試返回

new {MainObj = l, InterestPercentage = (your calculated field)} 

或創建一個對象,它將具有與上述類似的結構。這將幫助您避免所有的財產設置。

+0

結束了這樣做。謝謝 – Prescott 2013-05-07 15:40:03

0

當您通過OData公開此查詢時,您將不得不重寫它以使用連接。 OData不支持連接,但支持擴展,即在單個請求中獲取相關集合。爲了能夠擴展您的OData查詢,您需要在元數據中定義各自的關係,即,如果您想使用ListingKey作爲連接字段從Properties和Interest獲取數據,則需要在這些表之間建立關係在ListingKey(或引用這兩個表的另一個表)上。

0

你不使用join,你可以模擬通過使加入你自己的顯式連接:

var results = from prp in context.properties 
       from inr in context.interest // cross join 

       // your own join phrase 
       where inr.ListingKey == (prp.InterestPercentage ?? 0) 
        && inr.userId == "" 
       select new { ... };