How to check if ObjectResult collection was empty?
-
16-06-2021 - |
Question
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)
Solution
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.
var custId = last_customer_id_collection.FirstOrDefault<int?>();
if(custId.HasValue)
DoStuffWithId();
else
DoStuffWithNullResult();
Small Example that demonstrates the potentialy confusing behaviors of Nullables This will print:
"Null!", "No Value but no NullReferenceException" and then "Oops, InvalidOperationException"
List<int?> values = new List<int?>();
var test = values.FirstOrDefault();
if (test == null)
Console.WriteLine("Null!");
if (test.HasValue)
Console.WriteLine(test.Value);
else
Console.WriteLine("No Value but no NullReferenceException");
try
{
int value = test.Value;
}
catch(InvalidOperationException)
{
Console.WriteLine("Oops, InvalidOperationException");
}