I am trying to run the following in LINQ
double totalDistance = (from g in db.Logs join
h in db.Races on g.raceId equals h.RaceId
where g.userId == id select h.distance).Sum();
However get an error:
The cast to value type 'Double' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
I tried to add on ?? 0
; such that:
double totalDistance = (from g in db.Logs join
h in db.Races on g.raceId equals h.RaceId
where g.userId == id select h.distance).Sum() ?? 0;
As suggested in other posts however this yields an error:
operator '??' cannot be applied to operands double or int
Any suggestions?
EDIT: my model
namespace RacePace.Models
{
public class Race
{
public int RaceId { get; set; }
[DisplayName("Race Setting")]
public string place { get; set; }
[DisplayName("Distance (km)")]
public double distance { get; set; }
[DisplayName("Date")]
public DateTime date { get; set; }
[DisplayName("Commencement Time")]
public DateTime timeStarted { get; set; }
[DisplayName("Active")]
public Boolean active { get; set; }
[DisplayName("Description")]
public string description { get; set; }
[DisplayName("Creator")]
public int UserId { get; set; }
}
}
You should make you distance nullable double in your model to make ?? work. From http://msdn.microsoft.com/en-us/library/ms173224.aspx:
The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference type
So changing your model to
public double? distance { get; set; }
should make ?? work
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With