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

TypeExampleC# Code
One-to-Many1 User โ†’ Many OrdersUser { List<Order> Orders }
One-to-One1 User โ†’ 1 ProfileUser { UserProfile Profile }
Many-to-ManyMany Students โ†’ Many CoursesStudent { 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: 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.

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.

Comments on Relationships (0)

No comments yet. Be the first to share your thoughts!