Reputation: 3707
I'm still learning Linq and I came across a query I'm not able to get to work. I get an error about DateTime?
does not contain a definition for AddMinutes
. The Estimated_Out field is a nullable DateTime
type. The Offset_Dept_Time_Mins
is an integer field type.
Here is the SQL. It takes a field (Estimated_Out
) and adds an accepted offset time (Offset_Dep_Time_Mins
) divided by the minutes in a 24hr period and formats it as just minutes and seconds using a 24 hour format. An example of the returned time would be (17:45).
select to_char(ESTIMATED_OUT + (OFFSET_DEP_TIME_MINS/1440),'HH24:MI') as ETD
FROM TableName
Here is what I'm trying in Linq. In this example I'm first just trying to get it to add 10 minutes. Once I have that I was going to try to add the offset divided by the minutes of the day.
var result = (from f in TableName
select new
{
ETD=f.ESTIMATED_OUT,
ETD2=f.ESTIMATED_OUT.AddMinutes(10)
}).ToList();
How can I add minutes to the estimated time and then how would i format it? I'm assuming I would have to convert it to a Sting somehow once the time is correct?
Upvotes: 0
Views: 4071
Reputation: 3707
Thanks for the input. I wanted to share what looks like is going to work based on everyone's suggestions.
ETD=f.ESTIMATED_OUT.GetValueOrDefault(DateTime.Now).AddMinutes((double)f.OFFSET_DEP_TIME_MINS/1440).ToString(@"HH:mm")
Upvotes: 0
Reputation: 46331
You can't call .AddMinutes()
on DateTime?
because it's not DateTime
. To do that you first have to get the internal value (f.ESTIMATED_OUT.Value
) or some default value instead (using GetValueOrDefault(x)
).
If you do choose to get the internal value without defaults, make sure you first filter out null rows:
from f in TableName
where f.ESTIMATED_OUT.HasValue
select new
{
ETD=f.ESTIMATED_OUT,
ETD2=f.ESTIMATED_OUT.Value.AddMinutes(10)
}).ToList();
If you want to use some default value instead, use this:
from f in TableName
select new
{
ETD=f.ESTIMATED_OUT,
ETD2=f.ESTIMATED_OUT.GetValueOrDefault(DateTime.Now).AddMinutes(10)
}).ToList();
Upvotes: 0
Reputation: 5689
First of all, you're comparing a DateTime
to DateTime?
. You need to check if f.ESTIMATED_OUT is null or get a default value, THEN do your comparison.
Second of all - if you are using the Entity Framework or LINQ to SQL,
LINQ can't translate .AddMinutes(10)
to the appropriate SQL Statement. Either do your date math outside of the LINQ statement or use the SqlFunctions.DateAdd()
instead
Upvotes: 1
Reputation: 3845
You need to convert your nullable DateTime to a DateTime before you can add minutes to it:
var result = (from f in TableName
select new
{
ETD=f.ESTIMATED_OUT,
ETD2=((DateTime)f.ESTIMATED_OUT).AddMinutes(10)
}).ToList();
Upvotes: 0