ASP.NET Core MVC Interview Question #194

How would you handle validation that depends on the database?

Senior Practical MVC Scenarios & Production Architecture Senior Advanced

Quick Interview Answer

Keep Data Annotations focused on simple model-level rules and perform database-dependent validation through an application service or validator. The controller can add resulting errors to ModelState and redisplay the form.

Detailed Explanation

Keep Data Annotations focused on simple model-level rules and perform database-dependent validation through an application service or validator. The controller can add resulting errors to ModelState and redisplay the form.

Database validation does not replace database constraints. If uniqueness or integrity must be guaranteed under concurrency, enforce it in the database and handle the resulting conflict gracefully.

Code Example

if (await _users.EmailExistsAsync(
        model.Email, model.Id, token))
{
    ModelState.AddModelError(
        nameof(model.Email),
        "Email is already in use.");
}

if (!ModelState.IsValid)
    return View(model);