EF Core Relationships
One mistake deletes your entire prod DB. 6 mins.
Your First "Aha" Moment: Foreign keys are just C# properties. EF Core wires them up.
1. The 3 Relationship Types
| Type | Example | C# Code |
|---|---|---|
| One-to-Many | 1 User โ Many Orders | User { List<Order> Orders } |
| One-to-One | 1 User โ 1 Profile | User { UserProfile Profile } |
| Many-to-Many | Many Students โ Many Courses | Student { List<Course> Courses } |
2. One-to-Many - 90% of Your Job
public class User {
public int Id { get; set; }
public List Orders { get; set; } // Navigation
}
public class Order {
public int Id { get; set; }
public int UserId { get; set; } // FK
public User User { get; set; } // Navigation
}
Rule: EF creates FK by convention: UserId โ User.Id. Don't fight it.
3. Cascade Delete - The Prod Killer
modelBuilder.Entity()
.HasOne(o => o.User)
.WithMany(u => u.Orders)
.OnDelete(DeleteBehavior.Cascade); // Default!
What happens: _db.Users.Remove(user) โ Deletes user AND all his orders.
If wrong: Delete 1 admin = delete 10k orders. Company loses money. You lose job.
Career-Killer Mistake #1: Using Cascade on everything.
Example:
Fix: Use
Example:
Order โ Payment. If you delete old order for GDPR, you also delete payment record. Audit fails. Legal sues. Fix: Use
DeleteBehavior.Restrict for financial data. Let DB throw FK error. Handle it.
Stop Here. Think. Many-to-Many before EF Core 5 needed join entity. Now it's automatic.
Next section: Shadow Properties. The FK column you don't see in C# but exists in DB.
Next section: Shadow Properties. The FK column you don't see in C# but exists in DB.
Quick Check ๐ง
โ ๏ธ This is not the end
This is V1 Draft Version
We are upgrading. Don't judge book by its cover.
Picture abhi baki hai mere dost ๐ฌ
We're still adding topics. Current content is first version draft, we are on internal review.
We need your feedback to make this production-grade. Found a bug? Tell us.
EF Core Basics Complete! You covered Intro โ DbContext โ Migrations โ LINQ โ Relationships.
Up next: Advanced EF Core, Performance, Raw SQL, Interceptors. We're building it. Stay tuned.
Up next: Advanced EF Core, Performance, Raw SQL, Interceptors. We're building it. Stay tuned.
No comments yet. Be the first to share your thoughts!