If you have a nullable value in the database, you should use Nullable<T> and not enter Magic Numbers . But if BookId is a (primary) key, it probably should not be null (in addition, it is used as a foreign key).
UPDATE
In order to query the database and find a suitable record, several solutions. I prefer to throw an exception because it usually indicates an error if the application tries to get a record that does not exist.
Book book = Book.GetById(id);
What would you do in this case with a null return value? Probably, the code after this line wants to do something with the book, and in the case of null, the method usually can’t do anything else
- throws an exception, which can be better done in
GetById() (in addition, the caller may have more contextual information about the exception) - returns immidiatly with a zero code or an error code that requires processing by the caller, but this effectively rethinks the exception handling system.
If this is absolutely true, not finding a suitable entry, I suggest using the TryGet template.
Book book; if (Book.TryGetById(out book)) { DoStuffWith(book); } else { DoStuffWithoutBook(); }
I believe this is better than returning null, because null is a kind of magic value, and I don't like to see implementation details (the link type or the NULL value type can take a special value called null) in business logic. The disadvantage is that you lose compositional ability - you can no longer write Book.GetById(id).Order(100, supplier) .
The composition is backward below, but it has a very big problem - the book can be deleted between calling Exists() and GetById() , so I highly recommend not to use this template.
if (Book.Exists(id)) { Book book = Book.GetById(id).Order(100, supplier); } else { DoStuffWithoutBook(); }
source share