如何选择通过实体框架的下一个和previous实体?实体、如何选择、框架、previous

2023-09-04 00:23:42 作者:罗密欧与猪过夜

我有一个Web应用程序,显示一些实体的细节,让我们把它叫做登录。实体是从SQL Server通过实体框架4加载。

I have a web app that displays the details of some entity, let's call it Log. The entity is loaded from SQL Server via Entity Framework 4.

我想提供'下一个'和'previous链接走过日志双向。

I would like to provide 'next' and 'previous' links to walk through logs bidirectionally.

日志是由两个属性/列下令:

Logs are ordered by two properties/columns:

日期 时间 Date Time

这两个列可能包含,并没有保证唯一性。如果这两个值都为空,那么为了保证一个稳定的排序我命令被数据库编号,这是保证非空的和独特的。

Both of these columns may contain null, and there is no guarantee of uniqueness. If both of these values are null, then in order to guarantee a stable sort I order by the database Id, which is guaranteed to be non-null and unique.

此外,还有实际上可能没有一个实体之前或之后给定登录

Furthermore there may not actually be an entity before or after a given Log.

有some其他questions该地址做这与SQL直接。我想知道如何与实体框架做到这一点,最好做只有一个行程到数据库带回了几场为这双日志的(ID ,标题等)。

There are some other questions that address doing this with SQL directly. I'd like to know how to do this with the Entity Framework, ideally making only a single trip to the DB to bring back a few fields for this pair of Logs (id, title, etc).

推荐答案

我不知道,如果这个工程,但我们把它一试:

I'm not sure if this works but let get it a try:

var query =(
        from l in context.Logs
        where l.UserId == log.UserId &&
             (    l.Date < log.Date
              || (l.Date == log.Date && l.Time < log.Time)
              || (l.Date == log.Date && l.Time == log.Time && l.Id < log.Id)
             )
        orderby l.Date descending, l.Time descending
        select l
    ).Take(1)
    .Concat((
        from l in context.Logs
        where l.UserId == log.UserId &&
             (    l.Date > log.Date
              || (l.Date == log.Date && l.Time > log.Time)
              || (l.Date == log.Date && l.Time == log.Time && l.Id > log.Id)
             )
        orderby l.Date, l.Time
        select l
    ).Take(1));