I am running a linq query that should throw an exception (based on my understanding), but it does not. There is no item in the database that fits the parameters of the query.
The following does not throw an exception, but simply returns null:
from i in Items
where i.ItemID == 25
select i.Values.First(v => v.AttribID == 69)
The following does throw an exception as expected:
(from i in Values
where i.ItemID == 25
where i.AttribID == 69
select i).First()
Through testing several different forms of the query, the only difference I can find is that .First doesn't seem to throw the exception when the lambda expression inside of returns nothing, but when .First is invoked with no parameters, it does. Please help me understand why.
To clarify...
from i in Items
where i.ItemID == 25
select i
...returns 1 item.
See linqPad results below when testing these queries:
The first query says:
Filter
Items
to only include those withItemId == 25
and from each filtered resulti
, select the first itemv
insidei.Values
such thatv.AttribID == 69
.
Here First
will not throw if e.g. Items
is empty because "from each filtered result i
" will process exactly zero items, so First
will never be called.
The second query says:
Filter
Values
to only include those withItemId == 25
andAttribId == 69
and give me the first matching item.
It's obvious that in this case if no matching items exist First
cannot give you a meaningful result and will throw.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With