When to check for zeros?
When you know that id is supposed to exist, as in the example below, is it good to check for zeros?
var submission = _ctx.Submissions.FirstOrDefault(p => p.Id == id);
submission.Done = true;
_ctx.Submissions.Attach(submission);
_ctx.Entry(submission).State = EntityState.Modified;
_ctx.SaveChanges();
source to share
If id is supposed to exist, you are not checking for null. In fact, in this case, you should request such
_ctx.Submissions.Single(p => p.Id == id);
A single method throws an exception if the item is not found. On the other hand, if you are building a WebAPI, or have a specific page not found as the ID is sent by the client (i.e. something outside your code might come up), you can use SingleOrDefault and then check for null and return the appropriate HTTP status code or redirect to the appropriate page. Basically, if zero results are not confirmed, you should check and respond accordingly. If the arguments causing null values are generated by the code, you should NOT check for null and the actual request in such a way that it does not result in null, since otherwise you just close the error in the code.
This is my opinion, which is the result of my personal experience. Please note that not everyone agrees, as can be seen from the various answers to a question I posted on programers.stackexchange.com a while ago - https://softwareengineering.stackexchange.com/questions/147480/should-one-check- for-null-if-he-does-not-expect-null
source to share
If you feel that there should always be an object, and that the object in question does not exist, that means there is a bug in the program, then you should use First
not FirstOrDefault
. This means that if one of your assumptions for this code is violated, you will be informed quickly, loudly and as close to the source of the problem as possible.
FirstOrDefault
should be used when no items exist for the query in question, resulting in a return value being returned null
. If you are in this position, the program should work correctly if the request does return null
or whatever you need for the program to function properly.
What you want to avoid is to put yourself in a position where the program (incorrectly) assumes that the request always has at least one element, but where you use it anyway FirstOrDeafult
. You are getting NullReferenceExceptions here, which can do additional debugging work to figure out where the actual problem is (a query without the elements that the elements should have had).
source to share
FirstOrDefault
documents your intent as "the result I expect may contain no elements". In such a case, you should check null
and do some reasonable backups. Throwing exceptions at this point would look strange.
It looks like you are not expecting an empty result in your case, so use First
and handle the exception somewhere higher up the call stack, or even allow default exception handling.
source to share