I have this piece of code which check the last customer_id from the db.
ObjectResult<int?> last_customer_id_collection = MainForm.eggsContext.ExecuteStoreQuery<int?>("select MAX(customer_id) from customers");
Then I get the next id required like this
new_customer_id = last_customer_id_collection.FirstOrDefault<int?>().Value + 1;
It's working, HOWEVER when dealing with a new empty db the statment last_customer_id_collection.FirstOrDefault<int?>()
throws an InvalidOperationException.
How can I check if last_customer_id_collection was empty without try catch?
(p.s. I was trying to check if last_customer_id_collection.Any<int?>()
or last_customer_id_collection.Count<int?>()
or DefaultIfEmpty etc. but everything I try causes this exception)
You get an InvalidOperationException because
Nullable<T>.HasValue
would return false.You will need to modify the code to not call
.Value
if the query return value is null.Small Example that demonstrates the potentialy confusing behaviors of Nullables This will print:
"Null!", "No Value but no NullReferenceException" and then "Oops, InvalidOperationException"