如何将此SQL转换为LINQ或Lambda表达式?

时间:2012-04-09 12:43:58

标签: sql linq lambda

这是我在下面的SQL查询:
你能帮助我把它改成一个更干净的吗?

SELECT [PurchaseRequestID], [ProjectID],[FullName]
FROM PurchaseRequest
  WHERE [PurchaseRequestID] IN
    (SELECT [PurchaseRequestID] FROM PurchaseRequestDetail )
    AND [PurchaseRequestID] NOT IN
      (SELECT [PurchaseRequestID] FROM [PurchaseOrder] )

虽然我已经成功转换了这个,但我认为这是不可读的,需要重写:

var query = from a in db.PurchaseRequests
where
   (from b in db.PurchaseRequestDetails
    select new
    {
        b.PurchaseRequestID
    }).Contains(new { a.PurchaseRequestID }) &&
!(from c in db.PurchaseOrders
    select new
    {
        c.PurchaseRequestID
    }).Contains(new { a.PurchaseRequestID })
select a;

感谢

3 个答案:

答案 0 :(得分:2)

你真的不需要所有这些匿名对象。使用let关键字来引入临时变量,而不是直接对子查询执行操作。

from a in db.PurchaseRequests
let b = from b in db.PurchaseRequestDetails select b.PurchaseRequestID
let c = from c in db.PurchaseOrders select c.PurchaseRequestID
where b.Contains(a.PurchaseRequestID) && !c.contains(a.PurchaseRequestID)
select a;

答案 1 :(得分:1)

var query = from a in db.PurchaseRequests
where
   db.PurchaseRequestDetails.Any(x => x.PurchaseRequestID == a.PurchaseRequestID) &&
   !db.PurchaseOrders.Any(x => x.PurchaseRequestID == a.PurchaseRequestID)
select a;

答案 2 :(得分:0)

如果您设置了导航属性,则可以像这样编写查询:

IQueryable<PurchaseRequest> query = 
  from purchaseRequest in myDataContext.PurchaseRequests
  where purchaseRequest.PurchaseRequestDetail.Any()
  where !purchaseRequest.PurchaseOrder.Any()
  select purchaseRequest;

如果你喜欢这个lambda /方法风格......

IQueryable<PurchaseRequest> query2 = myDataContext.PurchaseRequests
  .Where(purchaseRequest => purchaseRequest.PurchaseRequestDetail.Any())
  .Where(purchaseRequest => !purchaseRequest.PurchaseOrder.Any());