views:

107

answers:

4

Hi,

I am using the Repository Pattern for my application. I have a class User. User is identified by Email. The UserRepository contains a method CreateUser(User user). There is a business rule saying that users should have a unique Email.

I want to implement a transaction which first checks whether an email is in use and if not, the user is created. Where should I put this code which is responsible for checking the uniqueness of the Email?

This is definitely a business rule; it is business logic. I think it is not correct to put this check in my UserRepository implementation.

A: 

Assuming you're using a database for storage, you should definitely add a unique constraint on the e-mail column in the database.

Mehmet Aras
+6  A: 

This sort of thing typically goes in either (1) a service or (2) directly into the schema as a database constraint (and frequently both).

Using a service, you don't access the Repository directly from client code; you call a service which does the useful operations for you.

For example, something like:

public class UserService : ... {
  private Repository<User> _userRepository;

  public void CreateUser(User u) {
    // Verify that the user's email is unique.
    if ( ... ) {
      _userRepository.Create(u);
    }
  }
}
John Feminella
+2  A: 

If you're building an application large enough to warrent a repository pattern then you'll want to put this validation as close to the data as possible, probably a database constraint such as a unique index/key. This prevents situations of bugs leaking into code later due to corrupt data.

Ollie Saunders
+1 absolutely - put it in the database - do never rely on the app to do too much validation....
marc_s
A: 

Check out this excellent article on Simple Talk:

Five Simple Database Design Errors You Should Avoid

See in Section 4:

Enforcing Integrity via applications

Proponents of application based integrity usually argues that constraints negatively impact data access. They also assume selectively applying rules based on the needs of the application is the best route to take. .....

The solution is simple.

Rely on nothing else to provide completeness and correctness except the database itself. By nothing, I mean neither users nor applications external to the database.**

So in your case - a unique constraint on your e-mail column should really be modelled in the database. That's the best place to put that piece of business logic, and will save you from a lot of grief in the long run.

Marc

marc_s