如何执行左连接并排除与LINQ中的子查询匹配的结果?

时间:2013-10-09 20:27:31

标签: sql linq

需要将此sql查询转换为LINQ

SELECT *
FROM 
    parcels p
    LEFT JOIN leases l ON p.parcels_pk = l.parcels_fk
WHERE 
    l.parcels_fk IS NULL 
    AND p.parcels_pk NOT IN (SELECT parcels_fk FROM application_parcels)
ORDER BY parcel

尝试了这个:

var qry = from p in db.Parcels
          join l in db.Leases on p.Id equals l.pk_parcel
          where l.pk_parcel == null 
                && !(from ap in db.ApplicationParcels 
                     select ap.ParcelId).Contains(p.Id)
                     orderby p.Name

1 个答案:

答案 0 :(得分:3)

             // SELECT * FROM parcels
var result = from p in parcels
             // LEFT JOIN leases ON p.parcels_pk = l.parcels_fk
             join llj in leases on p.parcels_pk equals llj.parcels_fk into lj
             from l in lj.DefaultIfEmpty()
             // WHERE l.parcels_fk IS NULL
             where l.parcels_fk == null
             // AND p.parcels_pk NOT IN (...)
               && !application_parcels.Any(x => x.parcels_fk == p.parcels_pk)
             // ORDER BY [p.]parcel
             order by p.parcel
             select new { parcel = p, lease = l };

假设我的架构正确。

但未来:

  • 首先提供你尝试过的东西(显示努力)。
  • 看看LINQPad,它非常有帮助。