我有一个左外连接(如下)按预期返回结果。我需要将“右”表的结果限制为“第一”命中。我能以某种方式做到吗?目前,我得到了两个表中每条记录的结果,无论我在右表(照片)中有多少结果,我只想看到左侧表(项目)中的一个结果。
var query = from i in db.items
join p in db.photos
on i.id equals p.item_id into tempPhoto
from tp in tempPhoto.DefaultIfEmpty()
orderby i.date descending
select new
{
itemName = i.name,
itemID = i.id,
id = i.id,
photoID = tp.PhotoID.ToString()
};
GridView1.DataSource = query;
GridView1.DataBind();
最佳答案
这将为您完成这项工作。
from i in db.items
let p = db.photos.Where(p2 => i.id == p2.item_id).FirstOrDefault()
orderby i.date descending
select new
{
itemName = i.name,
itemID = i.id,
id = i.id,
photoID = p == null ? null : p.PhotoID.ToString();
}
当我根据我自己的模型生成它时,我得到了这个 sql(并且在投影中没有名称和第二个 id 列)。
SELECT [t0].[Id] AS [Id], CONVERT(NVarChar,(
SELECT [t2].[PhotoId]
FROM (
SELECT TOP (1) [t1].[PhotoId]
FROM [dbo].[Photos] AS [t1]
WHERE [t1].[Item_Id] = ([t0].[Id])
) AS [t2]
)) AS [PhotoId]
FROM [dbo].[Items] AS [t0]
ORDER BY [t0].[Id] DESC
查询计划时,显示子查询是通过这个join实现的:
<RelOp LogicalOp="Left Outer Join" PhysicalOp="Nested Loops">
关于c# - 如何将 LINQ 左外连接限制为一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/492683/