2010-07-26 30 views
0

我有一個表Product。產品與ProductDescription以一對多的關係相關。每個產品的ProductDescription可以有多行。如果產品描述有多個翻譯,它將有多行。產品與語言有多對一的關係。語言具有語言代碼(en,es等)以及LanguageId(也可以在ProductDescription中找到)。將條件應用於Linq中的預先加載(包含)請求到實體

我想讓我的用戶能夠請求產品,並進一步告訴應用程序只返回特定語言的描述。

我在Linq to Entities中完成了這個任務。我想產生這樣的SQL:

SELECT * FROM Product p 
JOIN ProductDescription pd ON p.ProductId = pd.ProductId 
JOIN (SELECT * FROM Language WHERE AlternateCode = 'es') AS l ON pd.LanguageId = l.LanguageId 

(AlternateCode是語言代碼字段名)

有誰知道如何做到這一點?我現在留下的是拉下所有的語言,然後用Linq過濾掉它們,這肯定不太理想。我可以在一個循環中獲得每個產品的語言代碼,但這需要多次SQL往返,這也是我不想要的。

感謝任何幫助!

+0

哦,如果有人想提起「Any()」,我忘了提及。這在這種情況下不起作用,因爲它將過濾器應用於影響我的根結果集的ProductDescription。我不希望更少的結果,因爲我只是想防止不需要的語言被填充。 – omatase 2010-07-26 01:30:00

回答

0

使用projection,不急於加載。

var q = from p in Context.Product 
     select new ProductPresentation 
     { 
      Id = p.Id, 
      // etc. 
      Description = new ProductDescriptionPresentation 
      { 
       Language = (from l in p.ProductDescription.Languages 
          where l.AlternateCode.Equals("es", StringComparison.OrdinalIgnoreCase) 
          select l).FirstOrDefault(), 
       // etc. 
      } 
     }; 
+0

這是我以前用LinqToSql的東西,但在這個特定的情況下,我使用Linq to Entities和PredicateBuilder。我想盡管這不是謂詞的一部分,而是選擇語句。我可能仍然遇到麻煩。如果我這樣做,我會發佈一個更完整的例子。 – omatase 2010-07-26 15:04:52

+0

這在L2S和L2E中的工作原理完全相同。 PredicateBuilder在L2E中需要'AsExpandable',但其他方式一切正常。 – 2010-07-26 15:06:22

+0

我很難找出它適合的地方。也許這是因爲我沒有做。選擇我認爲可能需要投影的查詢。這是我的查詢。 「WherePredicate」是PredicateBuilder。 VAR查詢= inventoryRepository.Products .INCLUDE( 「ProductDescriptions」) .INCLUDE( 「ProductAllowedWarehouses」) .INCLUDE( 「ProductToCategories」) .INCLUDE( 「PriceLevels」) .INCLUDE( 「AttachmentAssociations.Attachment」) .Expandable() 。Where(wherePredicate); – omatase 2010-07-27 14:38:41