Reputation: 3707
I've done a lot of searching and can't quite find what I'm trying to accomplish. When using Linq - Entities I'm get the difference between the UTC time an a value in the database that is the estimate of when something should leave. I think the subtraction of my ETO subtracted from UTC is working correctly however I need to convert it to minutes. The current subtraction (due to it being a DateTime) is being display in hours and minutes but I need to display as 240 instead of 2:00 for a two hour difference.
The problem is that I'm getting an error when I try to divide my results by 60 or try to format using .ToString(@"mm"). When I try to multiple by 1440 (mins in a 24 hr period) I get an error can't convert system.TimeSpan to Double. If I try not to cast to a double I get an error that an operand of "*" can't be applied to a TimeSpan. Trying to set it to .ToString(@"mm") it tells me there is no overload for .ToString.
Here is my select on a query. Currently my MinutesLeft is being displayed as 02:32:38.7914913 for 2 hours, 32 min, 38 secs.
select new
{
EstimateOut=f.ESTIMATED_OUT,
UTC=DateTime.UtcNow,
MinutesLeft=(DateTime.UtcNow - f.ESTIMATED_OUT),
//MinutesLeft=(double)(DateTime.Now - f.ESTIMATED_OUT)*1440,
//MinutesLeft=(DateTime.Now - f.ESTIMATED_OUT)*1440,
}).ToList();
Upvotes: 0
Views: 1317
Reputation: 3707
During my initial testing of this query I was using LinqPad set to "C# Statements". Now I'm actually applying this in my MVC project and I'm coming up with an error with the AddMinutes portion. The error says "LINQ to Entities does not recognize the method 'System.DateTime AddMinutes(double)' method, and this method cannot be translated to a store expression'.
So I have a few questions. I searched on this error and found some posts saying I should be using something like this System.Data.Entity.DbFunctions.AddMinutes("DATETIMEHERE", 180). However, when I add this in LinqPad I get "DbFunctions does not exist in the namespace". When I add it to the query in the MVC project I get basically the same message. So far I haven't found anything to help address that message. Do I need to add a reference to something from NuGet? I've already installed EntityFramework through NuGet.
Second question, would the following statement be correct once I get all the references done correctly? ETD=System.Data.Entity.DbFunctions.AddMinutes(f.ESTIMATED_OUT, f.OFFSET_DEP_TIME_MINS + (f.OFFSET_DEP_TIME_MINS/1440))
Upvotes: 0
Reputation: 1564
You can use the property TotalMinutes to get your result:
MinutesLeft = (DateTime.UtcNow - f.ESTIMATED_OUT).TotalMinutes;
The value you get is a nullable type. You can access it this way:
MinutesLeft = (DateTime.UtcNow - f.ESTIMATED_OUT).Value.TotalMinutes;
Since nullable types can be null, you should make sure that it does have value:
TimeSpan? t = (DateTime.UtcNow - f.ESTIMATED_OUT);
var MinutesLeft = t.HasValue? t.Value.TotalMinutes : -1;
Upvotes: 3