0

下面是我的 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;

谢谢

4

3 回答 3

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;
于 2012-04-09T12:56:50.147 回答
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;
于 2012-04-09T12:56:51.100 回答
0

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

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

或者如果你喜欢这个 lambda/method 风格......

IQueryable<PurchaseRequest> query2 = myDataContext.PurchaseRequests
  .Where(purchaseRequest => purchaseRequest.PurchaseRequestDetail.Any())
  .Where(purchaseRequest => !purchaseRequest.PurchaseOrder.Any());
于 2012-04-10T06:03:07.733 回答