maztt
maztt

Reputation: 12294

asp.net mvc avoid duplication

I have a Users table in which no two same users can exists , what is the best way to do this error free?

What I did is that I wrote a check for duplication in the controller, but someone said to me it's not a right thing to do. He said put unique on database table? I have implemented this on several other controllers as well. Do I ought to change it?

Upvotes: 2

Views: 404

Answers (2)

Prashant Lakhlani
Prashant Lakhlani

Reputation: 5806

There are several places where you should do this.

  • at database table level: Use email as username and mark it as unique constrant
  • at model validation level you can check for the email and return validation error
  • at client side, you can place some code using async request that will check for duplicate email or username in real time when user enters username in textbox

-- edit --

It is suggested to place all three for better validations. Inconsistent data is the worst thing for your system than anything else. Because what I think is, correct data = good quality

-- end edit --

please keep in mind that validation code should be placed at model and to learn how to write manageable OO code you can see example of mvc store front.

hope this will help

Upvotes: 3

Paddy
Paddy

Reputation: 33857

It is much better to enforce your data constraints at a database level, wherever possible. consider the following situation:

2 requests to create a user with the same name, at around the same time.

  1. Request 1 checks DB to see if exists - user does not;
  2. Shortly after, request 2 checks DB to see if exists - user does not;
  3. Request 1 creates this user.
  4. Request 2 creates a duplicate user.
  5. Bang. Everything stops working the way you expect it to.

As for whether to use a unique constraint, or to have this as a primary key, is another question and very much depends on your situation (because you do have a primary key of some kind on this table, don't you?)

Upvotes: 5

Related Questions