How to limit a LINQ left outer join to one row

后端 未结 4 735
南方客
南方客 2020-12-13 12:53

I have a left outer join (below) returning results as expected. I need to limit the results from the \'right\' table to the \'first\' hit. Can I do that somehow? Currently,

4条回答
  •  遥遥无期
    2020-12-13 13:30

    This will do the job for you.

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

    I got this sql when I generated it against my own model (and without the name and second id columns in the projection).

    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
    

    When I asked for the plan, it showed that the subquery is implemented by this join:

    
    

提交回复
热议问题