Tutorials Entity Framework Core Tutorial
Validation with EF Core
Validation with EF Core: free step-by-step lesson with examples, common mistakes, and interview tips — part of Entity Framework Core Tutorial on Toolliyo Academy.
On this page
Entity Framework Core Tutorial · Lesson 29 of 100
Validation with EF Core
Beginner ✓ → Intermediate → Advanced → Professional
Intermediate · 2 — Data & queries · ~6 min · Module 3: CRUD Operations
What is this?
Validation ensures entity data meets rules before SaveChangesAsync. Data annotations, IValidatableObject, and interceptors can reject invalid Product or Customer rows early.
Why should you care?
ShopNest cannot save to the database negative prices or empty customer emails — validation returns friendly errors before SQL throws generic constraint violations.
See it live — copy this example
Paste into a .NET project with EF Core packages, then run with LocalDB/SQL Server (dotnet ef / dotnet run).
public class Product : IValidatableObject
{
public int Id { get; set; }
public string Name { get; set; } = "";
public decimal Price { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext ctx)
{
if (Price <= 0)
yield return new ValidationResult("Price must be positive.", new[] { nameof(Price) });
}
}
// Before save:
var errors = _context.ChangeTracker.Entries<Product>()
.SelectMany(e => e.Properties.Select(p => e))
.ToList();
_context.SaveChanges(); // throws DbUpdateException if annotations fail
What happened?
- IValidatableObject runs custom rules.
- EF can validate annotations on SaveChanges if configured.
- Invalid entities throw before SQL executes.
Practice next
- Add [Required] and Range to Product and Customer.
- build IValidatableObject for cross-field rules.
- Catch DbUpdateException and map to ProblemDetails in API.
- Add ISaveChangesInterceptor to validate all Added Product entries centrally.
- Test invalid Price with TryValidateObject in a unit test without database.
Remember
Validate before SaveChanges when possible. Annotations and IValidatableObject integrate with EF. Combine with SQL constraints for integrity.
ShopNest seller upload
Bulk CSV import validates each Product row before AddRangeAsync.
Outcome: Bad rows rejected with row numbers instead of cryptic SQL errors.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!