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?
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.
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.
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 .
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();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With