Here is my sql query as follow
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
And I try to convert this sql statement into linq as follow
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) };
But problem its giving me imageName
in a nested list but i want that imageName
just as a string .
I also check by using quick watch and in following image you can see that imageName
appearing in inner list .
Use the OrderByDesecnding() amd First() query operators. No - LINQ to SQL does the optimization of doing everything on the server side and getting you only one record. Great! That works, it produces a nice "select top 1" T-SQL.
By default, LINQ queries return a list of objects as an anonymous type. You can also specify that a query return a list of a specific type by using the Select clause.
While the LINQ methods always return a new collection, they don't create a new set of objects: Both the input collection (customers, in my example) and the output collection (validCustomers, in my previous example) are just sets of pointers to the same objects.
Instead of Take(1)
which returns sequence IEnumerable<string>
, use FirstOrDefault()
which returns single string value (or null if there is no results). Also don't create anonymous type for subquery result:
imageName = (from soh in db.tblProductImages where soh.product_id == e.ProductId select soh.image_name).FirstOrDefault()
BTW FirstOrDefault()
generates TOP(1)
SQL.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With