如何将以下SQL查询转换为Lambda表达式?

时间:2014-05-21 04:02:19

标签: c# sql sql-server linq lambda

我有一个以下SQL查询,我已经转换为Linq,并且不知道如何将此查询转换为Lambda Expression。

SQL

 SELECT BP.*
   FROM [ams].[BackgroundPackage] AS BP
        INNER JOIN [ams].[BkgPackageHierarchyMapping] AS BPHM
            ON BP.BPA_ID = BPHM.BPHM_BackgroundPackageID
        INNER JOIN [ams].[BkgOrderPackage] AS BOP
            ON BPHM.BPHM_ID = BOP.BOP_BkgPackageHierarchyMappingID
        INNER JOIN [ams].[BkgOrder] AS BO ON BOP.BOP_BkgOrderID = BO.BOR_ID
  WHERE BO.BOR_MasterOrderID = @OrderID
    AND BO.BOR_IsDeleted = 0

Lambda版本  //如何编写上述查询的lambda版本

Linq版本

var packageData =
    (from ep in _dbContext.BackgroundPackages
     join e in _dbContext.BkgPackageHierarchyMappings on ep.BPA_ID equals e.BPHM_BackgroundPackageID
     join t in _dbContext.BkgOrderPackages on e.BPHM_ID equals t.BOP_BkgPackageHierarchyMappingID
     join s in _dbContext.BkgOrders on t.BOP_BkgOrderID equals s.BOR_ID
     where s.BOR_MasterOrderID == orderId
     select new
            {
                Id = ep.BPA_ID,
                Name = ep.BPA_Name,
            });

1 个答案:

答案 0 :(得分:2)

您的SQL的lambda查询(简明表示法)将是:

var lambdaQuery = _dbContext.BackgroundPackages
    .Join(_dbContext.BkgPackageHierarchyMappings, ep => ep.BPA_ID, e => e.BPHM_BackgroundPackageID, (ep, e) => ep)
    .Join(_dbContext.BkgOrderPackages, ep => ep.BPHM_ID, t => t.BOP_BkgPackageHierarchyMappingID, (ep, t) => new { ep, t})
    .Join(_dbContext.BkgOrders, ept => ept.t.BOP_BkgOrderID, s => s.BOR_ID, (ept, s) => new { ept.ep, s })
    .Where(eps => eps.s.BOR_MasterOrderID  == orderId && eps.s.BOR_IsDeleted == 0)
    .Select(eps => eps.ep);