0

我的应用程序有一个内置的日历系统,它们的数据库模式如下所示:

CalendarItem( CalendarItemId bigint, Start datetime, Length int, Blargh nvarchar(MAX) )

Start是事件开始时的 UTC 日期时间值,是事件Length的长度(以秒为单位)。全天事件从 0000h 开始,长度为 86400。

我将 Linq 与 Entity Framework 一起使用,并且我想查找日期范围内的事件。很容易找到在两个日期时间之间开始的事件,但我不知道如何找到也在两个日期时间之间结束的事件。

这是我当前的代码:

public IEnumerable<CalendarItem> GetCalendarItems(DateTime from, DateTime to) {

    var events = from c in db.CalendarItems
                 where c.Start >= from && c.Start <= to
                 orderby c.Start
                 select c;

    return events;
}

如果我使用的是 T-SQL,我需要使用DATEADD添加Length秒数来Start给出一个End日期时间,这样就可以了,但我认为我不能在 Linq 中做到这一点。我能做些什么?

4

3 回答 3

2

用 ToList() 函数编辑包括:

如果我没看错,你会想要:

var events = (from c in db.CalendarItems
             where c.Start >= from && c.Start <= to
             orderby c.Start
             select c).ToList();
events = events.Where(e => e.Start.AddSeconds(Length) <= to);

return events;

然后,这将为您提供在指定日期范围内开始和结束的事件。

有关 DateTime.AddSeconds() 的更多信息,请访问此链接

于 2013-01-07T02:30:47.260 回答
1

您需要先调用ToList(),然后才能使用该DateTime.AddSeconds功能。否则编译器会抱怨找不到该AddSeconds函数,因为您的 LINQ 查询将被转换为 SQL 并且 SQL 不包含此DateTime.AddSeconds函数。

var events = (from c in db.CalendarItems
             where c.Start >= from && c.Start <= to
             orderby c.Start
             select c).ToList();
events = events.Where(e => e.Start.AddSeconds(Length) <= to);
return events;

编辑:更正了我的逻辑,答案现在与 IronMan84 相同。

于 2013-01-07T02:30:07.713 回答
0

我评估了这些.ToList方法,但它们效率低下,因为在修改它以返回发生的事件(无论它们是在某个时间段内开始还是结束)之后,它会从数据库中获取许多不相关的结果。

我还查看了 SqlFunctions 方法,但它们在 EF1.0 中不存在。

我最终在我的实体上下文中使用了带有强类型导入的 Sproc。它并不完美,但它比替代品更好。

当项目最终升级到 .NET4 时,我将切换到 SqlFunctions。无论如何,感谢您的所有建议!

于 2013-01-07T06:38:16.533 回答