Don Thomas Boyle
Don Thomas Boyle

Reputation: 3045

Linq: Nullable Object must have Value

My query is as follows:

int ID = db.Q_Table.Find(item.PassedInID).ID;

I already found a solution for my issue, however i am wondering why i must write it like so

1.

Nullable(int) ID = db.Q_Table.Find(item.PassedInID).ID;

2.

db.Q_Table.Where(w => w.PassedInID== item.PassedInID).Select(s => s.ID ).SingleOrDefault();

It wouldn't let me put int int he < in the above code -.-...

I am curious why i have to code it to a nullable int? I really didn't want to code it like 2nd solution because its more code :). Yes i have made sure there are values in the database and from the below image you can see my database doesn't accept nulls.

Thanks for any answers

enter image description here

Upvotes: 2

Views: 517

Answers (4)

Habib
Habib

Reputation: 223402

There is a difference between int and Nullable<int> or int?, you can't directly assign a Nullable<int> to int (Nullable<T>), Consider:

int? x = 123;
int y = x; //This would be an error

But you can use null-coalescing operator

int? x = 123;
int y = x ?? 0;

Now for your case, your ID seems to be a mapped to column in database which allows null. That will map to C# Nullable<int>, if you want to assign the result to an int you can do:

int ID = db.Q_Table.Find(item.PassedInID).ID ?? 0;

That will give your variable the value of ID or 0 if it is null.

Upvotes: 2

Hogan
Hogan

Reputation: 70538

I guess you could do something like the following, it is a little less code:

int? t;

int ID = (t = db.Q_Table.Find(item.PassedInID).ID) == null ? -1 : t;

Of course, now you will have to handle -1 ID as a special case later in your code. I expect you just want a nullable int.

Upvotes: 0

that's probably because db.Q_Table.Find returns a nullible int.

you can probably also do the following if you wanted to

int? ID = db.Q_Table.Find(item.PassedInID).ID;

Upvotes: 0

Anders Abel
Anders Abel

Reputation: 69280

ID is not an int but rather a Nullable<int> (or short form int?).

This is typically the case when the underlying database column is nullable.

There is also no < operator defined on an int?. If you want to do that, you have to check for the presence of a value first:

db.Q_Table.Where(w => w.PassedInID.HasValue && w.PassedInID.Value == item.PassedInID)
  .Select(s => s.ID ).SingleOrDefault();

Upvotes: 1

Related Questions