Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting null error LINQ; cannot then use? [duplicate]

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; }
}
}
like image 541
NickP Avatar asked Nov 03 '22 01:11

NickP


1 Answers

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

like image 122
Alex Avatar answered Nov 13 '22 22:11

Alex