In the new Entity Framework Code First MVC tutorial series there are some examples of what has come to be called fluent API method calls. This term refers to code in which a series of method calls are chained together. The Creating a More Complex Data Model tutorial briefly explains what this code does, but some readers of the tutorial expressed an interest in getting a more in-depth explanation, so I am providing that here, along with links to the relevant API reference documentation.
Here is the code block in question:
public class SchoolContext : DbContext { public DbSet<Course> Courses { get; set; } public DbSet<Department> Departments { get; set; } public DbSet<Enrollment> Enrollments { get; set; } public DbSet<Instructor> Instructors { get; set; } public DbSet<Student> Students { get; set; } public DbSet<OfficeAssignment> OfficeAssignments { get; set; } protected override void OnModelCreating (DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); modelBuilder.Entity<Instructor>() .HasOptional(p => p.OfficeAssignment) .WithRequired(p => p.Instructor); modelBuilder.Entity<Course>() .HasMany(c => c.Instructors) .WithMany(i => i.Courses) .Map(t => t.MapLeftKey("CourseID") .MapRightKey("InstructorID") .ToTable("CourseInstructor")); modelBuilder.Entity<Department>() .HasOptional(x => x.Administrator); } }
The first of the mapping API method calls specifies a one-to-zero-or-one relationship between the Instructor and OfficeAssignment entities:
Instructor
OfficeAssignment
modelBuilder.Entity<Instructor>() .HasOptional(p => p.OfficeAssignment).WithRequired(p => p.Instructor);
Instructor entity
Instructor.OfficeAssignment
The second statement specifies the table and column names for the join table of the many-to-many relationship between the Instructor and Course entities. Code First can configure the many-to-many relationship for you without this code, but if you don't call it, you will get default names such as InstructorInstructorID for the InstructorID column.
Course
InstructorInstructorID
InstructorID
modelBuilder.Entity<Course>() .HasMany(c => c.Instructors).WithMany(i => i.Courses) .Map(t => t.MapLeftKey("CourseID") .MapRightKey("InstructorID") .ToTable("CourseInstructor"));
Course.Instructors
Courses
In the third statement, the HasOptional statement specifies a one-to-zero-or-one relationship between the Department and Instructor tables, represented by the Department.Administrator navigation property:
Department
Department.Administrator
modelBuilder.Entity<Department>() .HasOptional(x => x.Administrator);
WithRequired
-- Tom Dykstra ASP.NET Developer Guidance