9

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?

user11081980
  • 3,059
  • 4
  • 30
  • 48

2 Answers2

9

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();
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
  • I've always wondered, is there a good reason to use unidirectional one-to-many (when it's not a design choice)? In other words, is there a downside to always using bidirectional? – 41686d6564 stands w. Palestine May 08 '19 at 21:14
  • 1
    @AhmedAbdelhameed Only when materialized entity instances are used for data transfer with serializers having issues with reference "loops". Bu that usage is bad practice anyway. EF itself has no issues with that, and from modelling/querying point of view bidirectional perfectly represents a relationship with both ends multiplicity. – Ivan Stoev May 09 '19 at 01:14
  • So the question arises: does it matter on which entity I will do the configuration? I think that it does not matter on which side, does it ? – Eru Oct 28 '19 at 13:07
  • @Eru As mentioned in the answer, if both entities have navigation properties, it doesn't matter. Otherwise it should be on the entity having the navigation property. All this applies to EF6, in EF Core you can configure the relationship from any of the entities. – Ivan Stoev Oct 28 '19 at 13:13
1

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
Sampath
  • 63,341
  • 64
  • 307
  • 441