Question

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...

  1. Best to catch the SqlException thrown if I try to insert a username which already exist.
  2. 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!

Was it helpful?

Solution

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.

OTHER TIPS

I would say it is best to handle the exception. The database is designed to handle the uniqueness of the user name, so I imagine it can do it more efficiently than you can. Also it adds portability and cohesion to your system. If you add users in more than one place you will have to duplicate the username checking or create a method and basically you will end up rewriting what the database engine has already written.

Additionally to what Samuel said, you'd need to make sure that nobody enters a record that could conflict with yours between your check and adding the record to the database. You could achieve this with a lock, but then you've got to catch exceptions caused by the lock.

As for duplicating stuff in the business rules and the database, I'm in favour of the database habing as much consitency checking in place as is required, even if this does duplicate some stuff in the business layer. The more tightly locked your database is against invalid data the better. It protects you against access to your database via other tools than your app, such as a support guy making changes in the database using SSMS to correct a data problem reported by a user.

I second what samuel said. The most efficient way is to leave it to database. All other options are more time and resource consuming....

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top