1

I'm using fluent validation in my ASP.NET Core Web API. While this works perfectly for scenarios like empty or greater than scenarios, I want to validate database keys / ids.

For example, while adding an expense I want to validate whether provided income account exists or not.

I could see two approaches here:

  1. Validate inside fluent validation for such key / ids
  2. Validate while adding entity to database

What are the performance implications (if any) of validating database keys / ids inside fluent validator?

2 Answers 2

0

Your requirement is - validate whether provided income account exists or not. So, for that you need to check the request data with existing data, which means need to access database connection instance (DB context). Then it is good to do it when you are saving data to DB (may be inside of repository or else service layer).

Inject DB context to validator is not a good practice as I think.

Sign up to request clarification or add additional context in comments.

Comments

0

Validating Inside FluentValidation is a hard pass cause it's more headache than needed,

RuleFor(x => x.AccountId).MustAsync(async (id, _) => await _repo.ExistsAsync(id));

why this is a bad idea:

  • Extra database hits for every validation - not great for performance.

  • Can lead to the N+1 query problem, especially when dealing with collections.

  • Runs sequentially, so you lose out on batching optimizations.

  • Tightly couples validation logic with database access, which isn’t clean.

I'd suggest validating at the service layer

// After standard validation
if (!await _accountRepo.ExistsAsync(expense.AccountId)) return BadRequest();

and it works better cause:

  • Optimized queries - I can batch-check multiple IDs at once.
  • Single transaction scope - keeps my DB operations efficient.
  • Cleaner architecture - validation stays focused on rules, and data integrity is handled where it should be.

I’d say keep FluentValidation for business rules (format, required fields, etc.) and check database constraints in the service layer where I can actually optimize them.

FluentValidation for business rules, service layer for Database checks.
Trust me, your future self will thank you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.