2013-01-07 30 views
0

我的应用程序有一个内置的日历系统,并为他们的数据库架构是这样的:LINQ的 - 开始有开始和长度属性日历事件

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

Start是UTC日期时间价值的情况下启动时,并且Length是以秒为单位的事件的长度。全天活动开始于0000h,长度为86400.

我正在使用Linq与实体框架,我想查找日期范围内的事件。很容易找到在两个日期时间之间开始的事件,但我不知道如何在两个日期时间之间找到也是结束的事件。

这里是我当前的代码:

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,我需要使用DATEADDLength秒添加到Start给一个End日期时间,那么这将工作,但我不我认为我可以在Linq做到这一点。我能做什么?

+1

请参阅http://msdn.microsoft.com/en-us/library/system.data.objects.sqlclient.sqlfunctions.dateadd.aspx –

回答

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的。

+0

您的events.Where子句将始终返回所有内容。 e.Start总是小于e.Start.AddSeconds(长度)。请参阅我的答案以获得更好的解决方案。 – IronMan84

+0

@ IronMan84谢谢你是对的。感谢您将我的答案合并为一个答案。 – rexcfnghk

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()的更多信息,请访问this link

0

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

我也看了一下SqlFunctions的方法,但它们不在EF1.0中。

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

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