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

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

问题描述

我有一个网络应用程序显示一些实体的详细信息,我们称之为 Log 。实体通过实体框架4从SQL Server加载。



我想提供下一个和上一个链接,以便双向进行日志。



日志由两个属性/列排列:




  • 日期

  • 时间



这两列都可能包含 null ,并不保证唯一性。如果这两个值都为null,那么为了保证一个稳定的排序,我通过数据库 Id 命令,这个数据保证是非空和唯一的。 >

此外,在给定的 Log 之前或之后可能没有实体。



一些其他问题,用SQL解决这个问题直。我想知道如何使用实体框架来做到这一点,理想情况下,只需一次访问数据库即可为这对日志(id ,标题等)。

解决方案

我不知道这是否有效,但让我们试一试:

  var query =(
from l in context.Logs
其中l.UserId == log.UserId&& ;
(l.Date< log.Date
||(l.Date == log.Date&& l.Time< log.Time)
||(l 。日期== log.Date&& l.Time == log.Time&& l.Id< log.Id)

orderby l.Date descending,l.Time降序
选择l
).Take(1)
.Concat((
from l in context.Logs
其中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));


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.

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.

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));

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

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