LINQ - 使用查询表达式计算数据时间差

时间:2011-07-08 10:31:08

标签: linq datetime linq-to-entities

我使用EntityFramework 4,LINQ和C#。

我需要使用Linq从查询表达式在GridView中显示数据;我需要将项目anonymous type作为价值计算DateTime.UtcNow - cl.DateLocked注意:cl.DateLocked类型为DateTime,我需要知道这两个日期之间的差异天数。< / p>

使用此查询,我收到错误:

DbArithmeticExpression arguments must have a numeric common type. 

知道如何在Linq中做到这一点?如果Linq不允许它以不同的方式做到这一点?

感谢您的时间

var queryContentsLocked = from cl in context.CmsContentsLockedBies
                          join cnt in context.CmsContents
                          on cl.ContentId equals cnt.ContentId
                          join u in context.aspnet_Users
                          on cl.UserId equals u.UserId
                          select new
                          {
                            cl.DateLocked,
                            cnt.ContentId,
                            cnt.Title,
                            u.UserName,
                            u.UserId,
                            TimePan = DateTime.UtcNow - cl.DateLocked // Problem here!!!
                          };

3 个答案:

答案 0 :(得分:8)

var queryContentsLocked = from cl in context.CmsContentsLockedBies
                          join cnt in context.CmsContents
                          on cl.ContentId equals cnt.ContentId
                          join u in context.aspnet_Users
                          on cl.UserId equals u.UserId
                          select new
                          {
                            cl.DateLocked,
                            cnt.ContentId,
                            cnt.Title,
                            u.UserName,
                            u.UserId,
                            Days = SqlFunctions.DateDiff("day", cl.DateLocked, DateTime.UtcNow)
                          };

答案 1 :(得分:2)

不使用任何SqlFunction

var grandTotalWork = (from t in db.AssignmentHandymandetails
                           join ad in db.AssignmentDetails on t.assignment_detail_id equals ad.assignment_detail_id
                           where ad.assignment_id == Convert.ToInt32(Label_assignmentId.Text)
                            select new { startTime = t.started_time.Value.TimeOfDay, endTime = t.end_time.Value.TimeOfDay, TotalWorkTime = (t.started_time.Value.TimeOfDay.Duration() - t.end_time.Value.TimeOfDay.Duration()).Duration()});

然后你可以在你希望的GridView中绑定结果

答案 2 :(得分:-2)

试试这个:

DateTime.UtcNow.Subtract(cl.DateLocked).TotalDays