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
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments