DotNet98
DotNet98

Reputation: 747

LINQ and converting int? to int

Following gives me a cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?) error:

public class JobStructure
{
    public JobStructure()
    {
    }
    public JobStructure(int? jobId, int? parentJobId)
    {
        var js = from r in dbc.fnJobStructure(someParameter_to_database_function)
                 select new JobStructure
                 {
                    JobID = r.JobID //<-------------ERROR: cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)
                 };
    }
    public int JobID { get; set; }
}

JobID is of type Int, and r.JobId that's coming from my database is nullable (it shouldn't be but it is). That's beyond the point;

I just wanna know how to deal with this problem int? to int problem in general

thanks


EDIT

Actually, Never mind; I don't have a way of verifying the answers; the problem here is a fundamental one; I'm creating a whole new instance of my class inside the linq expression which will have its own JobId; so when I'm actually calling the JobStructure constructor, I am never assigning a proper jobId (a new instance in the linq gets created and once we're out of the constructor, that instance with the proper jobId is dead.) Anyways thought I'd let everyone know (I tried to delete my question, but it warned against it... so I'm leaving it here with the Edited note) cheers

Upvotes: 1

Views: 3598

Answers (1)

Ali Adravi
Ali Adravi

Reputation: 22723

JobID is not nullable so if your r.JobID will be null then it will not accept because JobID is not null able so better to use Zero(0) in case of null

JobID = r.JobID ?? 0;

or simply change JobID to nullable

 public int? JobID { get; set; }

Upvotes: 1

Related Questions