Configure Domain Classes in Entity Framework 6

We learned default Code-First Conventions in the previous section. Code-First builds the conceptual model from your domain classes using default conventions. EF 6 Code-First leverages a programming pattern referred to as convention over configuration. However, you can override these conventions by configuring your domain classes to provide EF with the information it needs. There are two ways to configure your domain classes:

  1. Data Annotation Attributes
  2. Fluent API

Data Annotations Attributes

Data Annotations is a simple attribute based configuration, which you can apply to your domain classes and its properties. These attributes are not only for EF but also used in ASP.NET web form or MVC and so, included in a separate namespace System.ComponentModel.DataAnnotations.

The following example demonstrates the use of some data annotation attributes:

[Table("StudentInfo")]
public class Student
{
    public Student() { }
        
    [Key]
    public int SID { get; set; }

    [Column("Name", TypeName="ntext")]
    [MaxLength(20)]
    public string StudentName { get; set; }

    [NotMapped]
    public int? Age { get; set; }
        
        
    public int StdId { get; set; }

    [ForeignKey("StdId")]
    public virtual Standard Standard { get; set; }
}

Note: Data annotation attributes do not support all the configuration options for Entity Framework. So, you can use Fluent API, which provides all the configuration options for EF.

Fluent API

Another way to configure domain classes is by using Entity Framework Fluent API. EF Fluent API is based on a Fluent API design pattern (a.k.a Fluent Interface) where the result is formulated by method chaining.

Fluent API configuration can be applied when EF builds a model from your domain classes. You can inject the Fluent API configurations by overriding the OnModelCreating method of DbContext in Entity Framework 6.x, as shown below:

public class SchoolDBContext: DbContext 
{
    public SchoolDBContext(): base("SchoolDBConnectionString") 
    {
    }

    public DbSet<Student> Students { get; set; }
    public DbSet<Standard> Standards { get; set; }
    public DbSet<StudentAddress> StudentAddress { get; set; }
        
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //Configure domain classes using modelBuilder here..

    }
}
        

You can use modelBuilder, an object of DbModelBuilder class to configure domain classes. The DbModelBuilder is called Fluent API because you can call different methods in a chain.

Visit the Fluent API configuration chapter for more detail.