在LINQ中的JOIN中使用AND

时间:2019-06-12 10:21:02

标签: c# entity-framework linq

我有这样的SQL:

SELECT Items.ItemCode AS code, Items.ItemName AS name, ISNULL(PLID.PriceOverule,Items.ItemPrice) AS price from tblPLItemsDetail PLID
INNER JOIN tblItems Items ON PLID.ItemID = Items.ItemID 
AND Items.ValidityTo IS NULL
WHERE PLItemID = @PLItemID 
AND PLID.ValidityTo IS NULL 
AND (PLID.ValidityFrom >= @LastUpdated OR @LastUpdated IS NULL)

我把它放在LINQ上

details = context.TblPlitemsDetail
          .Join(imisContext.TblItems, 
              p => p.ItemId, 
              i => i.ItemId, 
              (p, i) => new { TblPlitemsDetail = p, TblItems = i })
          .Where(r => r.TblPlitemsDetail.PlitemId == PLItemID 
              && r.TblPlitemsDetail.ValidityTo == null 
              && (r.TblPlitemsDetail.ValidityFrom >= Convert.ToDateTime(model.last_update_date) || model.last_update_date == null))
          .Select(x => new CodeNamePrice() 
          { 
              code = x.TblItems.ItemCode, 
              name = x.TblItems.ItemName, 
              price = (x.TblPlitemsDetail.PriceOverule == null) ? x.TblItems.ItemPrice.ToString() : x.TblPlitemsDetail.PriceOverule.ToString() 
          }).ToList();

我已经重写了大部分代码,但尚未在AND Items.ValidityTo IS NULL中实现JOIN谓词。

如何正确执行?

1 个答案:

答案 0 :(得分:2)

由于它是INNER JOIN,因此您可以在LINQ Items.ValidityTo IS NULL子句中指定额外的谓词(Where):

details = context.TblPlitemsDetail
          .Join(imisContext.TblItems, p => p.ItemId, i => i.ItemId, (p, i) => new { TblPlitemsDetail = p, TblItems = i })
          .Where(r => !r.TblItems.ValidityTo.HasValue) 
          .Where(r => r.TblPlitemsDetail.PlitemId == PLItemID && r.TblPlitemsDetail.ValidityTo == null && (r.TblPlitemsDetail.ValidityFrom >= Convert.ToDateTime(model.last_update_date) || model.last_update_date == null))
          .Select(x => new CodeNamePrice() { code = x.TblItems.ItemCode, name = x.TblItems.ItemName, price = (x.TblPlitemsDetail.PriceOverule == null) ? x.TblItems.ItemPrice.ToString() : x.TblPlitemsDetail.PriceOverule.ToString() }).ToList();