c# - Calculating time difference on datetime object in Entity Framework giving error -


i trying calculate time difference between 2 date , want day name of date.

for ex.: 4/7/2016

  • day: monday

here class:

public class attendance {       public int id { get; set; }       public nullable<system.datetime> startdatetime { get; set; }       public nullable<system.datetime> enddatetime { get; set; } } 

when trying this:

 var query = (from t in context.attendance               select new                {                  timediff=t.enddatetime.value.subtract(t.startdatetime.value).totalhours,                  day=system.startdatetime.tostring("dddd");               }).tolist(); 

error

linq entities not recognize method 'system.timespan subtract(system.datetime)' method, , method cannot translated store expression

i don't want below:

 var query = (from t in context.attendance.tolist().                   select new                    {                      timediff=t.enddatetime.value.subtract(t.startdatetime.value).totalhours,                      day=system.startdatetime.tostring("dddd");                   }).tolist(); 

i have datetime in format stored in tables , want expected output below shown in difference field:

startdatetime              enddatetime                difference ---------------------------------------------------------------- 2016-06-29 15:52:32.360    2016-06-29 15:52:36.970    00:00:04 2016-06-29 15:53:32.360    2016-06-29 15:55:36.970    00:2:00 2016-06-29 15:53:32.360    2016-06-29 16:55:36.970    01:02:00 

you can't use .net framework specific methods in ef queries unless there's canonical function defined them. there are, specific query:

try:

 var query = (from t in context.attendance                   select new                    {                                              timediff=sqlfunctions.datediff("hour",t.startdatetime, t.enddatetime),                      day=sqlfunctions.datename("weekday", t.startdatetime);                   }).tolist(); 

update

to reflect changes in wanted output in question:

 var query = (from t in context.attendance                   select new                    {                                              startdate = t.startdatetime,                      enddate = t.enddatetime,                             timediff=sqlfunctions.datediff("second",t.startdatetime, t.enddatetime),                   }).tolist(); 

and can use like:

foreach(var q in query) {   console.write($"{q.startdate:d} {q.enddate:d} {timespan.fromseconds(q.timediff):c}"); } 

Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -