Last post May 29, 2019 10:44 AM by MikeRM2
May 28, 2019 10:11 PM|MikeRM2|LINK
I am trying to figure out a check to prevent an error that I had this weekend. While testing a previously working section of my MVC application I got an unhandled exception, sequence contains no elements when I submitted my form to the server. I put
a breakpoint in to find out where the issue was, it I determined that it was because of hard coded values. I have two calls to the database to get IDs for values associated with the ID I am saving the information for. The error was caused by a mistype of
the data in the sql script that is seeding the database with some real and some dummy data.
What I want to do is prevent the unhandled exception or at least display an error that the hard coded value does not exist. That way if someone was to mistype or change the value in the database The end user wouldn't be completely stuck. While I hope
that the data wouldn't change and is typed correctly, mistakes happen. Here is a sample of what I was looking for that presented no data.
int rtid = _db.ReputationType.Where(a => a.ReputationTypeName == "Crafting").Select(a => a.ReputationTypeId).First();
Any thoughts on how to get around errors like this?
May 29, 2019 02:14 AM|nideeshm|LINK
int Count = _db.ReputationType.Where(a => a.ReputationTypeName == "Crafting").Count
if (count == 0)
throw new Exception();
return _db.ReputationType.Where(a => a.ReputationTypeName == "Crafting").select(x=>x...).First();
Please check this.
May 29, 2019 09:33 AM|PatriceSc|LINK
Or you could use FirstOrDefault which return 0 if the value is not found.
Not sure if this is your best option (reporting errors to IT can be better if the user can't really do anything anyway). Not sure about the context but it is a selectable user value it seems you could present available options rather than assign and hardcoded
default value from the code ???
May 29, 2019 10:44 AM|MikeRM2|LINK
Thanks for the answers. I used a combination of both. If the FirstOrDefault returned a 0, I threw a new exception with a custom message.