用于CROSS的LINQ表达式深层次应用两个级别

时间:2015-12-31 14:54:31

标签: c# linq linq-to-entities linq-expressions

LINQ相当新,我想弄清楚如何编写特定查询。我有一个数据库,其中每个CHAIN由一个或多个ORDERS组成,每个ORDER由一个或多个PARTIALS组成。数据库如下所示:

CREATE TABLE Chain
(
ID         int            NOT NULL  PRIMARY KEY CLUSTERED IDENTITY(1,1),
Ticker     nvarchar(6)    NOT NULL,
Company    nvarchar(128)  NOT NULL
)
GO

CREATE TABLE [Order]
(
ID      int             NOT NULL  PRIMARY KEY CLUSTERED   IDENTITY(1,1),
Chart   varbinary(max)  NULL,
-- Relationships
Chain   int             NOT NULL
)
GO

ALTER TABLE dbo.[Order] ADD CONSTRAINT FK_Order_Chain 
    FOREIGN KEY (Chain) REFERENCES dbo.Chain ON DELETE CASCADE
GO

CREATE TABLE Partial
(
ID           int     NOT NULL  PRIMARY KEY CLUSTERED IDENTITY(1,1),
Date         date    NOT NULL,
Quantity     int     NOT NULL,
Price        money   NOT NULL,
Commission   money   NOT NULL,
-- Relationships
[Order]       int     NOT NULL
)
GO

ALTER TABLE dbo.Partial ADD CONSTRAINT FK_Partial_Order
    FOREIGN KEY ([Order]) REFERENCES dbo.[Order] ON DELETE CASCADE

我想检索链,按照每个特定链的所有订单的所有部分中最早的日期排序。在T-SQL中,我会将查询编写为:

SELECT p.DATE, c.*
FROM   CHAIN c
CROSS  APPLY
(
    SELECT DATE = MIN(p.Date)
    FROM   PARTIAL p
    JOIN   [ORDER] o
      ON   p.[ORDER] = o.ID
    WHERE  o.CHAIN = c.ID
) AS p
ORDER BY p.DATE ASC 

我有一个实体框架上下文,其中包含DbSet< Chain>,DbSet< Order>和DbSet< Partial>。如何完成此语句以获得我想要的结果?:

IEnumerable<Chain> chains = db.Chains
                              .Include(c => c.Orders.Select(o => o.Partials))
                              .[WHAT NOW?]

谢谢!

1 个答案:

答案 0 :(得分:1)

  

。[现在怎么样?]

.OrderBy(c => c.Orders.SelectMany(o => o.Partials).Min(p => p.Date))

此处c.Orders确实将Chain加入Order,而o.SelectMany(o => o.Partials)加入Order加入Partial。一旦您有权访问Partial条记录,就可以使用任何聚合函数,例如Min(p => p.Date)