views:

94

answers:

2

Hi

What would be the best way to validate the uniqueness of a model? For example, making sure that only one user can have a certain username.

I am using the repository pattern to interact with the database, so should I place the check int there? If so, how do I get this to filter back to the model?

Thanks

A: 

Add a method to your UserRepository to lookup if the UserName is in use. The UserRepository could perform this validation on User.Save

public class UserRepository {

  private bool IsUserNameInUse(string userName) {
     return false;
  }

  private bool IsUserNameInUse(int userId, string userName) {
    // Verify no record other than the userid submitted is using the username
    return false;
  }

  public void Save(User userToSave) {
      if (IsUserNameInUse(userToSave.UserName)) throw new Exception();
  }

}
Jeff Fritz
+2  A: 

Are you also enforcing this constraint in the database?

Rich Rodriguez
No, not at the moment. Does LINQ to SQL undertsand that?
Ryan
That I don't know, but I usually put these kinds of constraints in the code and the database to be sure.
Rich Rodriguez