I'm trying to add a TimeSpan
to a DateTime
in a linq query using entity framework. I've got the following code:
EDIT
TimeSlots
is an ICollection<TimeSlot>
TimeSlot
has the properties DateTime Start
and TimeSpan Duration
var linq = from s in schedulesBase
join c in channelBase on s.ChannelId equals c.ChannelId
select new
{
...
TimeSlots = s.TimeSlots,
...
};
var timeslots = linq.SelectMany(t => t.TimeSlots);
return from s in timeslots
select new Resources.Event
{
...
end = DbFunctions.AddSeconds((DateTime?)s.Start, (Int32?)s.Duration.Seconds)
...
};
It compiles fine but doesn't add any time from s.Duration.Seconds
to end
.
Since the following code works
end = DbFunctions.AddSeconds((DateTime?)s.Start, 500)
and behaves as expected I must be doing something wrong with the conversion from TimeSpan
to seconds.
What am I doing wrong in the first case?
I suspect the problem is that you're using Seconds
instead of TotalSeconds
. The Seconds
property only gives a value in the range [-59, 59]
- so 5 minutes and 30 seconds would return 30, not 330, for example.
Try:
end = DbFunctions.AddSeconds((DateTime?)s.Start, (Int32?)s.Duration.TotalSeconds)
See more on this question at Stackoverflow