将datetime转换为dateordefault方法

时间:2015-01-09 22:23:39

标签: c# linq

我想制作一个可以保存日期和时间的系统。但是首先我想检查一下是否在同一天完成了手术。我在我的sql架构中创建了一个名为TruncateTime的函数,如下所示:

Create FUNCTION TruncateTime(@dateValue DateTime) RETURNS date
AS BEGIN
    RETURN CONVERT(date, @dateValue)
END

要检查我的c#脚本中的日期,我写道:

p = dc.pointages.SingleOrDefault(x => 
    x.userid.Equals(user_id) && 
    EntityFunctions.TruncateTime(x.date_pointage)== today.Date );

抛出的例外是:

  

类型' System.NotSupportedException'的例外情况发生在   System.Data.Linq.dll但未在用户代码中处理

我尝试了很多方法,现在我很困惑。

3 个答案:

答案 0 :(得分:0)

在对dbset执行linq查询时,不能使用自定义方法,但可以先将其设置为列表,然后进行比较。请注意,您在执行此操作时会获得所有记录,而不是在数据库中进行过滤。

p = dc.pointages
      .Where(x => x.userid.Equals(user_id))
      .ToList() // this will enable you to call custom methods in SingleOrDefault
      .SingleOrDefault(x => 
         EntityFunctions.TruncateTime(x.date_pointage)== today.Date );

答案 1 :(得分:0)

您应该可以使用DateTime对象的内置日期比较,例如:

p = dc.pointages.SingleOrDefault(x => 
    x.userid.Equals(user_id) && 
    x.date_pointage.Date.Equals(DateTime.Today.Date);

答案 2 :(得分:0)

使用LinqPad我为您创建了样本:

List<DateTime> dates = new List<DateTime>(){
        new DateTime(2015,1,1,0,0,1),
        new DateTime(2015,1,1,0,1,1),
        new DateTime(2015,1,2,0,2,2),
        new DateTime(2015,1,2,0,3,3),
        new DateTime(2015,1,3,0,4,4),
        new DateTime(2015,1,3,0,5,5),
        new DateTime(2015,1,9,8,7,6),
        new DateTime(2015,1,9,9,7,7),
        new DateTime(2015,1,9,10,8,8),
        new DateTime(2015,1,9,11,9,9),
        new DateTime(2015,1,9,12,10,10),
        new DateTime(2015,1,9,13,11,11)
        };

var qry = dates.Where(x=>x.ToString("yyyy/MM/dd")==new DateTime(2015,1,9).ToString("yyyy/MM/dd"));

qry.Dump();

结果:

2015-01-09 08:07:06 
2015-01-09 09:07:07 
2015-01-09 10:08:08 
2015-01-09 11:09:09 
2015-01-09 12:10:10 
2015-01-09 13:11:11 

注意:您需要根据需要进行更改;)

相关问题