如何选择通过实体框架的下一个和previous实体? [英] How to select the next and previous entities via Entity Framework?

查看:129
本文介绍了如何选择通过实体框架的下一个和previous实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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.

有<一href="http://stackoverflow.com/questions/203302/what-is-the-sql-for-next-and-$p$pvious-in-a-table">some其他<一href="http://stackoverflow.com/questions/2805375/how-to-select-$p$pvious-and-next-records-in-sql">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));

这篇关于如何选择通过实体框架的下一个和previous实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆