Relationships in EF Core

EF Core supports three main types of relationships between entities: One-to-One, One-to-Many, and Many-to-Many. These relationships are managed through navigation properties, which define how entities are connected and how EF Core handles data retrieval and manipulation.

These relationships can be configured using either the Fluent API or data annotations to define entity associations and ensure the correct schema is generated in the database.

 

Types:

One-to-One Relationship

One-to-Many Relationship

Many-to-Many Relationship

 

One-to-One Relationship

One entity is related to exactly one instance of another entity. Both sides of the relationship are tightly coupled.

For example, A Person can have only one Passport, and each Passport belongs to one Person.

 Configuration:

modelBuilder.Entity<Passport>()

    .HasOne(p => p.Person)

    .WithOne(p => p.Passport)

    .HasForeignKey<Passport>(p => p.PersonId);

 

Navigation Property:

Person has a navigation property to Passport, and Passport has a navigation property to Person.

 

  

One-to-Many Relationship

One entity is related to multiple instances of another entity. For example, a Customer can have many Orders, but each Order belongs to one Customer.

For example, A Customer has many Orders, and each Order is linked to one Customer.

Configuration:

modelBuilder.Entity<Order>()

    .HasOne(o => o.Customer)

    .WithMany(c => c.Orders)

    .HasForeignKey(o => o.CustomerId);

 

Navigation Property:

Customer has a collection of Orders, and each Order has a reference to Customer.

  

 

Many-to-Many Relationship

Many instances of one entity can be related to many instances of another entity. For example, many Students can enroll in many Courses, and many Courses can have many Students.

 For example, A Student can enroll in many Courses, and a Course can have many Students.

 Configuration:

modelBuilder.Entity<StudentCourse>()

    .HasKey(sc => new { sc.StudentId, sc.CourseId });

 

modelBuilder.Entity<StudentCourse>()

    .HasOne(sc => sc.Student)

    .WithMany(s => s.StudentCourses)

    .HasForeignKey(sc => sc.StudentId);

 

modelBuilder.Entity<StudentCourse>()

    .HasOne(sc => sc.Course)

    .WithMany(c => c.StudentCourses)

    .HasForeignKey(sc => sc.CourseId);

 

Navigation Property:

Student has a collection of StudentCourse (representing the relationship), and Course has a collection of StudentCourse.

 

Comments

Popular posts from this blog

Multiline to singleline IN C# - CODING

EF Core interview questions for beginners

EF Core interview questions for experienced