Non-model state validation filter
This is an everyday scenario of creating unique records in the DB. Suppose you have an entity User
. You have all the possible validation attributes set on it, but there's one you can't put on it. And that is whether the entity instance is unique.
Why do we need one anyway?
These are two most common processes with User
entity where validation is involved:
- Creating new users
- Updating user's data
So then you create a new user, you have to most probably check whether it's unique in your DB (either username or email or something similar; something has to be checked for uniqueness).
But when you do an update, uniqueness shouldn't be checked, because the user already exists in the DB.
How do we solve this?
By using an action filter on the Create
action. But since this kind of filter should be used will all different kinds of entities it's a wise thing to make it more generic and reusable, so we can actually use it will all kinds of entities.
This is how I've done it.