Configuring Properties and Types with the Fluent API: Samples

Description and code samples
Table of Contents
Operations
Specifing the database schema to use for all tables, stored procedures, etc (EF6 onwards)
How to do it
modelBuilder.HasDefaultSchema(“Training”);
Configuring a Primary Key
How to do it
modelBuilder.Entity<Student>().HasKey(e => e.StudentID);
Configuring a Composite Primary Key
How to do it
modelBuilder.Entity<Student>().HasKey(e => new { e.StudentID, e.StudentNumber });
Configuring Identity for Numeric Primary Keys
How to do it
modelBuilder.Entity<Student>().Property(e => e.StudentID)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Switching off Identity for Numeric Primary Keys
How to do it
modelBuilder.Entity<Student>().Property(e => e.StudentID)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Specifying the Maximum Length on a Property
How to do it
modelBuilder.Entity<Student>().Property(e => e.StudentName).HasMaxLength(50);
Configuring the Property to be Required (NOT NULL)
How to do it
modelBuilder.Entity<Student>().Property(e => e.StudentName).IsRequired();
Configuring an Index on one or more properties (EF6 onwards)

Creating indexes isn’t natively supported by the Fluent API, but you can make use of the support for IndexAttribute via the Fluent API.

Remarks

Refer to the references section for details about this topic.

How to do it
modelBuilder
    .Entity<Standard>()
    .Property(e => e.RegistrationNumber)
    .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute()));
Specifying Not to Map a Property to a Column in the Database
How to do it
modelBuilder.Entity<Student>().Ignore(t => e.Age);
Mapping a Property to a Specific Column in the Database
How to do it
modelBuilder.Entity<Student>()
    .Property(t => t.StudentName)
    .HasColumnName("Name");
Configuring a Foreign Key Association (foreign key property exists in the definition of the related class)
Remarks

If the foreign key is made up of multiple properties then an anonymous type including the properties is used: the properties must be specified in the same order that the the primary key properties were configured for the principal entity type.

How to do it
modelBuilder.Entity<Standard>()
    .WithMany(sta => sta.Students)
    .HasForeignKey(std => std.StandardId);
Configuring an Independent Association (foreign key property does not exists in the definition of the related class)
How to do it
modelBuilder.Entity<Standard>()
    .WithMany(sta => sta.Students)
    .Map(m => m.MapKey("StudentID"));
Configuring whether a String Property Supports Unicode Content
How to do it
modelBuilder.Entity<Student>()
    .Property(e => e.StudentName)
    .IsUnicode(false);
Configuring the Data Type of a Database Column
How to do it
modelBuilder.Entity<Student>()
    .Property(e => e.StudentName)
    .HasColumnType("varchar");
Configuring Properties on a Complex Type
How to do it

Option 1: Call Property on ComplexTypeConfiguration:

modelBuilder.ComplexType<ExtraInformation>()
    .Property(a => a.Data1)
    .HasMaxLength(20);

Option 2: Use the dot notation to access a property of a complex type.

modelBuilder.Entity<Student>()
    .Property(e => e.Info.Data1)
    .HasMaxLength(20);
Specifying That a Class Is a Complex Type
How to do it
modelBuilder.ComplexType<ExtraInformation>();
Customize Complex Type's Property Mappings
How to do it
  modelBuilder.ComplexType<ExtraInformation>()
                .Property(a => a.Data1)
                .HasColumnName("Data1");
Customize Complex Type's Property Mappings (per Entity)
How to do it
  modelBuilder.Entity<Student>()
                    .Property(e => e.Info.Data1)
                    .HasColumnName("StudentAddicionalData1");

  modelBuilder.Entity<Standard>()
                    .Property(e => e.Info.Data1)
                    .HasColumnName("StandardAddicionalData1");
Specifying Not to Map a Entity Type to a Table in the Database
How to do it
modelBuilder.Ignore<FakeStudent>();
Mapping an Entity Type to a Specific Table in the Database
How to do it
modelBuilder.Entity<Student>().ToTable("Student", "Training");
Mapping Properties of an Entity Type to Multiple Tables in the Database (Entity Splitting)

Entity splitting allows the properties of an entity type to be spread across multiple tables.

In the following example, the Student<(i> entity is split into two tables: Student and StudentInfo.

Entity splitting uses multiple calls to the Map() method to map a subset of properties to a specific table.

How to do it
modelBuilder.Entity<Student>()
    .Map(m =>
    {
        m.Properties(e => new { e.StudentID, e.StudentName });
        m.ToTable("Student");
    })
    .Map(m =>
    {
        m.Properties(t => new { e.StudentID, e.Info.Data1, e.Info.Data2, e.Info.Data3 });
        m.ToTable("StudentInfo");
    });

OR

// using inline delegate
modelBuilder.Entity<Student>()
    .Map(delegate(EntityMappingConfiguration<Student> studentConfig)
         {
           studentConfig.Properties(p => new { p.StudentId, p.StudentName });
           studentConfig.ToTable("Student");
         });

// using generic delegate
Action<EntityMappingConfiguration<Student>> studentMapping = m =>
         {
           m.Properties(p => new { p.StudentId, p.Data1, p.Data2, p.Data3 });
           m.ToTable("StudentInfo");
         };

modelBuilder.Entity<Student>().Map(studentMapping);
Mapping Multiple Entity Types to One Table in the Database (Table Splitting)
How to do it
modelBuilder.Entity<OfficeAssignment>()
    .HasKey(e => e.InstructorID); 

modelBuilder.Entity<Instructor>()
    .HasRequired(e => e.OfficeAssignment)
    .WithRequiredPrincipal(e => e.Instructor); 

modelBuilder.Entity<Instructor>().ToTable("Instructor"); 

modelBuilder.Entity<OfficeAssignment>().ToTable("Instructor");
Configuring Unconventional Foreign Keys

Code First may not recognize them as the foreign keys for the associations since their names are not aligned with the conventions that it has to infer foreign keys.

Therefore it may be required to use fluent API (or Data Annotations) to let Code First know about the foreign key properties.

How to do it
modelBuilder.Entity<Student>()
                .HasRequired(e => e.CurrentStandard)
                .WithOptional()
                .HasForeignKey(e => u.CurrentStandardId);

  modelBuilder.Entity<Student>()
                .HasRequired(e => e.PreviousStandard)
                .WithOptional()
                .HasForeignKey(e => u.PreviousStandardId);