2013-04-04 10 views
12

Ecco la mia query SQL come seguireSelezionare top 1 risultato da subquery in LINQ to 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 

e cerco di convertire questo istruzione SQL in LINQ come seguire

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) 
      }; 

Ma il problema relativo dare me imageName in un elenco annidato ma voglio quello imageName proprio come una stringa.

Controllo anche utilizzando l'orologio rapido e nell'immagine seguente è possibile vedere che imageName viene visualizzato nella lista interna.

here can be check quick watch result

risposta

31

Invece Take(1) che restituisce sequenza IEnumerable<string>, utilizzare FirstOrDefault() che restituisce valore stringa singola (o nullo se non ci sono risultati). Inoltre, non creare tipo anonimo per il risultato subquery:

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

BTW FirstOrDefault() genera TOP(1) SQL.

+0

ancora i suoi spettacoli nella colonna di visualizzazione della griglia {image_name = f55c1573_a658_420e_9d33_2a8d997bbd51.jpg} invece di f55c1573_a658_420e_9d33_2a8d997bbd51.jpg. Ho dato direttamente il risultato all'origine dati a gridview – rahularyansharma

+0

@rahularyansharma, per favore vedi un piccolo aggiornamento - questo perché hai creato il tipo anonimo per il risultato della subquery: 'new {soh.image_name}'. Dovresti semplicemente restituire il valore stringa. –

+1

Grazie! le sue opere ! – rahularyansharma