I'm adding parameters to insert information into a database and ran into a a potential null reference exception. By using the SingleOrDefault
LINQ expression, I thought if an instance had no Tag
called "Name" the Tag
would default to a null value. This is true as long as the instance has some sort of Tag
. If the instance has no tags at all, a null reference exception occurs. It's a rare occurrence, but I still need a better way to handle it. Is there a better way to solve this than catching the exception?
cmd.Parameters.AddWithValue("@Name", runningInstance.Tag.SingleOrDefault(t => t.Key == "Name").Value);
The only good way is to reconstruct your query a bit:
instance.Tag.Where(t => t.Key == "Name").Select(T => T.Value).SingleOrDefault();
That will do the trick.
I suspect your Tag
property is of type IDictionary<,>
. In that case, the best option to retrieve a value is:
if (instance.Tag.TryGetValue("Name", out TValue value))
{
// We have the value in the value. :)
}
else
{
// We don't.
}
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