LINQ - 以前的记录

时间:2016-02-26 18:18:54

标签: linq

所有

假设我有下表:

RevisionID, Project_ID, Count, Changed_Date
1           2          4      01/01/2016: 01:02:01
2           2          7      01/01/2016: 01:03:01
3           2          8      01/01/2016: 01:04:01
4           2          3      01/01/2016: 01:05:01
5           2          15      01/01/2016: 01:06:01

我根据Updated_Date订购记录。用户进入我的站点并编辑记录(RevisionID = 3)。由于各种原因,使用LINQ(使用实体框架),我需要获取表中的先前记录,即RevisionID = 2,因此我可以对“Count”执行计算。如果用户去编辑记录(RevisionID = 4),我需要选择RevisionID = 3。

我目前有以下内容:

var x = _db.RevisionHistory
           .Where(t => t.Project_ID == input.Project_ID)
           .OrderBy(t => t.Changed_Date);

这适用于根据Project_ID查找记录,但之后如何选择记录呢?

我正在尝试执行以下操作,但在一个LINQ语句中,如果可能的话。

var itemList = from t in _db.RevisionHistory
where t.Project_ID == input.Project_ID
orderby t.Changed_Date
select t;

int h = 0;

foreach (var entry in itemList)
{
if (entry.Revision_ID == input.Revision_ID)
{
break;
}
h = entry.Revision_ID;
}
var previousEntry = _db.RevisionHistory.Find(h);

2 个答案:

答案 0 :(得分:0)

希望我理解你想要的东西。 尝试:

var x = _db.RevisionHistory
       .FirstOrDefault(t => t.Project_ID == input.Project_ID && t.Revision_ID == input.Revision_ID -1)

或者,根据你所写的内容,但编辑:

_db.RevisionHistory
   .Where(t => t.Project_ID == input.Project_ID)
   .OrderBy(t => t.Changed_Date)
   .TakeWhile(t => t.Revision_ID != input.Revision_ID)
   .Last()

答案 1 :(得分:0)

以下是与您的代码等效的正确单个查询:

var previousEntry = (
    from r1 in db.RevisionHistory
    where r1.Project_ID == input.Project_ID && r1.Revision_ID == input.Revision_ID
    from r2 in db.RevisionHistory
    where r2.Project_ID == r1.Project_ID && r2.Changed_Date < r1.Changed_Date
    orderby r2.Changed_Date descending
    select r2
).FirstOrDefault();

生成以下SQL查询:

SELECT TOP (1) 
    [Project1].[Revision_ID] AS [Revision_ID], 
    [Project1].[Project_ID] AS [Project_ID], 
    [Project1].[Count] AS [Count], 
    [Project1].[Changed_Date] AS [Changed_Date]
    FROM ( SELECT 
        [Extent2].[Revision_ID] AS [Revision_ID], 
        [Extent2].[Project_ID] AS [Project_ID], 
        [Extent2].[Count] AS [Count], 
        [Extent2].[Changed_Date] AS [Changed_Date]
        FROM  [dbo].[RevisionHistories] AS [Extent1]
        INNER JOIN [dbo].[RevisionHistories] AS [Extent2] ON [Extent2].[Project_ID] = [Extent1].[Project_ID]
        WHERE ([Extent1].[Project_ID] = @p__linq__0) AND ([Extent1].[Revision_ID] = @p__linq__1) AND ([Extent2].[Changed_Date] < [Extent1].[Changed_Date])
    )  AS [Project1]
    ORDER BY [Project1].[Changed_Date] DESC