2014-02-20 77 views
1

如何將下列能夠產生正確結果的T-SQL查詢轉換爲C#中的LINQ表達式?如何將T-SQL轉換爲LINQ?

WITH CTE 
      AS (SELECT RN = ROW_NUMBER() OVER (PARTITION BY dbo.Product.ID ORDER BY dbo.Picture.UpdatedDate ASC) 
        ,Product.ID 
        ,Product.Name 
        ,Picture.Path 
       FROM Dbo.Product 
       INNER JOIN dbo.Product_Picture_Mapping 
        ON dbo.Product_Picture_Mapping.ProductID = dbo.Product.ID 
       INNER JOIN dbo.Picture 
        ON dbo.Picture.ID = dbo.Product_Picture_Mapping.PictureID) 
    SELECT ID AS 'ID' 
      ,Name AS 'Name' 
     FROM CTE 
     WHERE RN = 1 

我試過下面的代碼。

var result= (from c in cd.Product 
       join pp in cd.Product_Picture_Mapping 
          on c.ID equals pp.ProductID 
         join pcc in cd.Picture 
          on pp.PictureID equals pcc.ID 
         select new ProductViewModel() { PicturePath = pcc.Path, ProductName = c.Name, ProductID = c.ID}).ToList(); 
+0

你會得到什麼?例外?錯誤的數據?您的列輸出對於初學者的兩個查詢是不同的。 –

+0

所以,我只有一張圖片,其名稱是product1。 product1有4張圖片,我只通過sql查詢得到1行(這是我想要的) 但我通過lambda表達式獲得4行這對我來說是個問題。我想只有1行 –

+0

可能重複[Row \ _number over(Partition by xxx)in Linq?](http://stackoverflow.com/questions/9980568/row-number-over-partition-by-xxx-in- LINQ) – 2014-02-20 19:51:30

回答

0

看看以下工作:

var result= (from c in cd.Product 
       join pp in cd.Product_Picture_Mapping 
          on c.ID equals pp.ProductID 
       let pcc = pp.Pictures.FirstOrDefault() 
       select new ProductViewModel() 
       { 
        PicturePath = pcc.Path, 
        ProductName = c.Name, 
        ProductID = c.ID 
       }).ToList(); 

在你的餐桌名稱看,它看起來像你有一個多對多的表(product_picture_mapping)的EF可能能夠優化掉給你選項做類似:

var result = from c in cd.Product 
      let ppc = c.Pictures.FirstOrDefault() 
      select new ProductViewModel 
      { 
       PicturePath = pcc.Path, 
       ProductName = c.Name, 
       ProductID = c.ID 
      };