Friday, 1 November 2024

How do you configure relationships using Fluent API in EF Core?

In Entity Framework Core (EF Core), the Fluent API is a powerful way to configure relationships between entities in the OnModelCreating method of the DbContext class. While EF Core uses conventions to infer relationships by default, the Fluent API allows for precise customization, especially when setting up complex or non-standard relationships.

Here's how to configure various types of relationships using the Fluent API:

1. One-to-One Relationship

In a one-to-one relationship, each entity in the relationship has exactly one related entity.

Example: Configuring a one-to-one relationship between User and UserProfile.


public class User { public int Id { get; set; } public string Username { get; set; } public UserProfile UserProfile { get; set; } } public class UserProfile { public int Id { get; set; } public string Bio { get; set; } public int UserId { get; set; } // Foreign key public User User { get; set; } } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<User>() .HasOne(u => u.UserProfile) // User has one UserProfile .WithOne(p => p.User) // UserProfile has one User .HasForeignKey<UserProfile>(p => p.UserId); // Foreign key in UserProfile }

2. One-to-Many Relationship

In a one-to-many relationship, one entity can have multiple related entities, while each related entity has only one associated entity.

Example: Configuring a one-to-many relationship between Department and Employee.


public class Department { public int Id { get; set; } public string Name { get; set; } public ICollection<Employee> Employees { get; set; } } public class Employee { public int Id { get; set; } public string FullName { get; set; } public int DepartmentId { get; set; } // Foreign key public Department Department { get; set; } } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Department>() .HasMany(d => d.Employees) // Department has many Employees .WithOne(e => e.Department) // Each Employee has one Department .HasForeignKey(e => e.DepartmentId) // Foreign key in Employee .OnDelete(DeleteBehavior.Cascade); // Optional: specify cascade delete behavior }

3. Many-to-Many Relationship

In a many-to-many relationship, each entity can relate to multiple instances of another entity. In EF Core 5.0+, you can set up many-to-many relationships without explicitly defining a join table; EF Core creates it automatically.

Example: Configuring a many-to-many relationship between Student and Course.


public class Student { public int Id { get; set; } public string Name { get; set; } public ICollection<Course> Courses { get; set; } } public class Course { public int Id { get; set; } public string Title { get; set; } public ICollection<Student> Students { get; set; } } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Student>() .HasMany(s => s.Courses) // Student has many Courses .WithMany(c => c.Students) // Course has many Students .UsingEntity(j => j.ToTable("StudentCourses")); // Optional: specify table name for join table }

If you’re using EF Core 3.1 or earlier, you need to create an explicit joining entity (e.g., Enrollment) to set up a many-to-many relationship.

Additional Fluent API Configurations

The Fluent API provides additional configuration options:

  • Configuring Composite Keys:


    modelBuilder.Entity<Enrollment>() .HasKey(e => new { e.StudentId, e.CourseId }); // Composite primary key
  • Configuring Indices:


    modelBuilder.Entity<Employee>() .HasIndex(e => e.Email) .IsUnique();
  • Renaming Columns and Tables:


    modelBuilder.Entity<Employee>() .ToTable("tbl_Employees") .Property(e => e.FullName) .HasColumnName("EmployeeName");

Summary

The Fluent API in EF Core is a flexible way to configure relationships and customize entity mappings. Each relationship type—one-to-one, one-to-many, and many-to-many—has specific configurations using the Fluent API in the OnModelCreating method. This approach allows you to tailor EF Core’s default conventions to match specific data requirements and optimize database behavior, making it a powerful tool for fine-tuning relational models.

Share:

0 comments:

Post a Comment