I have a Users table, which has a Unique constraint on the username (for obvious reasons).
I am using an EF 4.0 DAL to populate the database, and in the process of coding the CreateUser() method.
Is it…
- Best to catch the SqlException thrown if I try to insert a username which already exist.
- Explicitly check for the username before I try to insert it to the database?
If you could also give reasons as to why, that would be great!
I would check if the record exists first. Unique key constraints are useful to guard against possible ways your application is allowing “bad” data through in the first place, but not the main stop for that. It’s generally a bad idea to use exceptions as a control flow mechanism (validation in this case) when it’s possible to avoid.
EDIT: To avoid confusion, I’m not saying don’t have the unique index at all. It should be there, but it shouldn’t be the primary means of checking for uniqueness.