Question

I just started with EF Code First. And I have a question about this. What is the advantage of defining relationships through the Fluent API?

When I create the database from my poco's (or entities) I already have one-to-many and/or many-to-many relationships between my tables.

For ex:

    public class School
    {
        public School()
        {
            Students = new List<Student>();
        }

        public Guid Id { get; set; }
        public string Name { get; set; }
        public List<Student> Student{ get; set; }
    }


public class Student
    {
        public Guid Id { get; set; }
        public string Firstname { get; set; }
        public string Lastname { get; set; }
        public Guid SchoolId{ get; set; }
        public School School{ get; set; }
    }

This creates already a relationship between Students and School. Does defining a relationship through the Fluent API gives advantages? Or not?

Thanks in advance!

Was it helpful?

Solution

The biggest advantage for using the Fluent API is when you need to customize something. In your example you have a one to many relationship between school and students. Your navigation properties describe that relationship exactly because you have a List on the School class and you have a School property on the Student.

Where the Fluent API becomes really helpful is if for some reason you want to keep that relationship but for some reason you don't want the navigation property to Students on the school:

public class School
{
    public School()
    {
        Students = new List<Student>();
    }

    public Guid Id { get; set; }
    public string Name { get; set; }
    // remove List<Student>
}

You can still describe this relationship using the Fluent API:

modelBuilder.Entity<Student>()
    .HasRequired(req => req.School)
    .WithMany() // no navigation property
    .HasForeignKey(fk => fk.SchoolId);

It is also useful in scenarios where you don't want to map the foreign key in the model itself. If you want to be able to override certain conventions of Entity Framework, sometimes the Fluent API is the only way to do that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top