2013-04-04 90 views
12

這裏是我的SQL查詢如下選擇在LINQ子查詢頂部1的結果爲sql

select enq_Id,enq_FromName, 
     enq_EmailId, 
     enq_Phone, 
     enq_Subject, 
     enq_Message, 
     enq_EnquiryBy, 
     enq_Mode, 
     enq_Date, 
     ProductId, 
     (select top 1 image_name 
     from tblProductImage as i 
     where i.product_id=p.product_Id) as imageName, 
     p.product_Name, 
     p.product_code  
from tblEnquiry as e 
inner join tblProduct as p ON e.ProductId=p.product_Id 
where ProductId is not null 

我嘗試這條SQL語句轉換成LINQ如下

var result = from e in db.tblEnquiries 
      join d in db.tblProducts 
        on e.ProductId equals d.product_Id      
      where e.ProductId != null 
      orderby e.enq_Date descending 
      select new { 
       e.enq_Id, 
       e.enq_FromName, 
       e.enq_EmailId, 
       e.enq_Phone, 
       e.enq_Subject, 
       e.enq_Message, 
       e.enq_EnquiryBy, 
       e.enq_Mode, 
       e.enq_Date, 
       d.product_Id, 
       d.product_Name, 
       imageName = (from soh in db.tblProductImages 
          where soh.product_id == e.ProductId 
          select new { soh.image_name }).Take(1) 
      }; 

但問題的捐贈我imageName嵌套列表,但是我想,imageName只是作爲一個字符串。

我也使用快速監視和下面的圖片檢查你可以看到,出現在內部列表imageName

here can be check quick watch result

回答

31

代替Take(1)它返回序列IEnumerable<string>,使用FirstOrDefault()它返回單個字符串值(或空如果沒有結果)。還沒有爲子查詢結果創建匿名類型:

imageName = (from soh in db.tblProductImages 
      where soh.product_id == e.ProductId 
      select soh.image_name).FirstOrDefault() 

BTW FirstOrDefault()產生TOP(1) SQL。

+0

仍然顯示在網格視圖列{image_name = f55c1573_a658_420e_9d33_2a8d997bbd51.jpg}而不是f55c1573_a658_420e_9d33_2a8d997bbd51.jpg。我直接因爲結果數據源的GridView – rahularyansharma 2013-04-04 12:16:33

+0

@rahularyansharma請參見小更新 - 這是因爲你的子查詢結果創建匿名類型:'新的{soh.image_name}'。你應該簡單地返回字符串值。 – 2013-04-04 12:18:58

+1

謝謝!其作品 ! – rahularyansharma 2013-04-04 12:19:23