Tutorials Entity Framework Core Tutorial
Constraints in EF Core
Constraints in 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 20 of 100
Constraints in EF Core
Beginner → Intermediate → Advanced → Professional
Beginner · 1 — Foundations · ~6 min · Module 2: Code First Approach
What is this?
Constraints enforce data rules at the database — primary keys, foreign keys, unique indexes, check constraints, and required columns. EF maps them via annotations, Fluent API, or migrations.
Why should you care?
ShopNest cannot allow two products with the same SKU or orders referencing missing customers — constraints are the last line of defense.
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).
modelBuilder.Entity<Product>(e =>
{
e.HasIndex(p => p.Sku).IsUnique();
e.Property(p => p.Name).IsRequired();
e.ToTable(t => t.HasCheckConstraint("CK_Product_Price", "Price > 0"));
});
modelBuilder.Entity<Order>(e =>
{
e.HasOne(o => o.Customer)
.WithMany(c => c.Orders)
.HasForeignKey(o => o.CustomerId)
.OnDelete(DeleteBehavior.Restrict);
});
What happened?
- Unique index on Sku blocks duplicates.
- Check constraint rejects non-positive prices.
- Restrict on CustomerId prevents deleting customers with orders.
Practice next
- Add unique SKU and price check constraint via Fluent API.
- Generate migration and verify CONSTRAINT lines in Up() SQL.
- Attempt duplicate Sku insert and read SQL error.
- Add filter unique index: HasIndex(p => p.Sku).IsUnique().HasFilter("[IsDeleted] = 0") for soft delete.
- Use HasAlternateKey on Customer.Email for uniqueness without making it PK.
Remember
Constraints protect data at the database layer. Fluent API expresses indexes, checks, and FK rules. Unique SKU is a classic e-commerce constraint.
ShopNest SKU integrity
Duplicate SKU insert during bulk import fails at SQL unique index despite passing CSV validation.
Outcome: Catalog stays consistent for Flipkart-scale search indexing.
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!