嵌套查询或子查询linq

时间:2011-12-22 13:10:44

标签: linq nested

我有两节课。票据和交易。一项法案由许多交易组成。我能够显示账单,我可以自己显示交易。但我想显示最后10张账单(这部分已完成),但每张账单都应显示其所有交易。

This part of the code is used to get all transactions of a bill
{        Bill bill = (Bill)Bills.Instance.GetBillsByCustomerID(id);

                //get all transactions of bill
                var transactions = from t in this._entities.Transactions
                                   where t.Bill.bID == bill.bID
                                   select new
                                   {
                                       t.Product.pName, t.tQty, t.tUnitPrice, t.Bill.bTotal, t.Bill.bTimestamp, t.Bill.bCustomerIDF
                                   };
    }

现在我希望下面的查询会有某种嵌套查询,其中获得每个账单的所有交易:(目前,这只显示10个账单 - 并且没有交易

{
            //returns top 10
            var bills = (from b in this._entities.Bills
                         where b.bCustomerIDF == id
                         orderby b.bTimestamp descending
                         select new { b.bTotal, b.bTimestamp, b.Customer.cName}).Take(10);
            return bills;
}

你能指导我一个简单的解决方案吗?谢谢

2 个答案:

答案 0 :(得分:1)

我相信你想要join into

 var bills = (from b in this._entities.Bills              
              join t in this._entities.Transactions on t.Bill.bID equals b.bID into tg
              where b.bCustomerIDF == id
              orderby b.bTimestamp descending
              select new 
              { 
                b.bTotal, 
                b.bTimestamp, 
                b.Customer.cName,
                Transactions = tg
              }
             ).Take(10);
 return bills;

答案 1 :(得分:1)

我原以为你应该能够在你的选择中添加如下内容:

transactions.Where(x=>x.Bill.bID == b.bID)`

据说我也认为这听起来像你的对象模型是错误的。我原本期望Bill有一个Transaction的集合。