Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to configure both sides of a relationship with Entity Framework with Fluent API?

I'm new to Fluent API. In my scenario, a Student can be in one Grade and a Grade can have many Students. Then, these two statements accomplish the same thing:

modelBuilder
.Entity<Student>()
.HasRequired<Grade>(s => s.Grade)
.WithMany(s => s.Students);

And:

modelBuilder
.Entity<Grade>()
.HasMany<Student>(s => s.Students)
.WithRequired(s => s.Grade);

My question is - how should I choose one statement over the other? Or do I need both statements?

like image 786
user11081980 Avatar asked Sep 24 '16 16:09

user11081980


People also ask

Why we use Fluent API with Entity Framework?

Fluent API is another way to configure your domain classes. The Code First Fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext. Fluent API provides more functionality for configuration than DataAnnotations.

What is fluent API in Entity Framework?

Entity Framework Fluent API is used to configure domain classes to override conventions. EF Fluent API is based on a Fluent API design pattern (a.k.a Fluent Interface) where the result is formulated by method chaining. In Entity Framework Core, the ModelBuilder class acts as a Fluent API.

How does Entity Framework handle many-to-many relationships in core?

Many-to-many relationships require a collection navigation property on both sides. They will be discovered by convention like other types of relationships. The way this relationship is implemented in the database is by a join table that contains foreign keys to both Post and Tag .


2 Answers

For bidirectional relationship like yours (i.e. when both ends have navigation properties), it doesn't really matter, you can use one or the another (you can also use both, but it's not recommended because it's redundant and may lead to out of sync between the two).

It really matters when you have unidirectional relationship because only With methods have parameterless overloads.

Imagine you don't have Grade.Students property. Then you can use only:

modelBuilder.Entity<Student>()
    .HasRequired(s => s.Grade)
    .WithMany();

and if you don't have Student.Grade property, then you can use only:

modelBuilder.Entity<Grade>()
    .HasMany(s => s.Students)
    .WithRequired();
like image 72
Ivan Stoev Avatar answered Sep 21 '22 12:09

Ivan Stoev


You just need one.This is more than enough for 1 : M relationship.

modelBuilder.Entity<Student>()
            .HasRequired<Grade>(s => s.Grade) //Student entity requires Grade 
            .WithMany(s => s.Students); //Grade entity includes many Students entities
like image 41
Sampath Avatar answered Sep 24 '22 12:09

Sampath