如何通过实体框架选择下一个和以前的实体? [英] How to select the next and previous entities via Entity Framework?
问题描述
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屋!