Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ - using a query expression to calculate data time difference

I use EntityFramework 4, LINQ, and C#.

I need display data in a GridView from a query expression using Linq; I need project as anonymous type a value calculate on fly DateTime.UtcNow - cl.DateLocked Note: cl.DateLocked is of type DateTime and I need to know how many days of difference between this two dates.

With this query I receive an error:

DbArithmeticExpression arguments must have a numeric common type. 

Any idea how to do it in Linq? If Linq does not allow it how to do it in a different way?

Thanks for your time

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!!!
                          };
like image 637
GibboK Avatar asked Jul 08 '11 10:07

GibboK


2 Answers

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)
                          };
like image 169
Magnus Avatar answered Nov 15 '22 10:11

Magnus


Without using any 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()});

then you can bind the result in GridView you wish

like image 30
Dipen Avatar answered Nov 15 '22 10:11

Dipen