C# 从linq to sql中的子查询中选择前1个结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15810699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select top 1 result from subquery in linq to sql
提问by rahularyansharma
Here is my sql query as follow
这是我的 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
And I try to convert this sql statement into linq as follow
我尝试将此 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)
};
But problem its giving me imageName
in a nested list but i want that imageName
just as a string .
但问题是它给了我imageName
一个嵌套列表,但我想要它imageName
作为一个字符串。
I also check by using quick watch and in following image you can see that imageName
appearing in inner list .
我还通过使用 quick watch 进行检查,在下图中您可以看到imageName
出现在内部列表中。
采纳答案by Sergey Berezovskiy
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:
而不是Take(1)
which 返回 sequence IEnumerable<string>
,使用FirstOrDefault()
which 返回单个字符串值(如果没有结果,则使用null )。也不要为子查询结果创建匿名类型:
imageName = (from soh in db.tblProductImages
where soh.product_id == e.ProductId
select soh.image_name).FirstOrDefault()
BTW FirstOrDefault()
generates TOP(1)
SQL.
顺便说一句,FirstOrDefault()
生成TOP(1)
SQL。