Code First - Fluent API

Code First - Fluent API

Fluent API is an advanced way of specifying model configuration that covers everything that data annotations can do and some more advanced configuration not possible with data annotations. Data annotations and the fluent API can be used together, but Code First gives precedence to Fluent API > data annotations > default conventions.

  • 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. Fluent API supports the following types of mappings.

Fluent API provides several essential methods to configure entities and their properties to override various Code First conventions. Below are some of them.

S.No. Method Name & Description
1. ComplexType TComplexType>
Registers a type as a complex type in the model and returns an object that can be used to configure the complex type. This method can be called multiple times for the same type to perform various configuration lines.
2. Entity
Registers an entity type as part of the model and returns an object that can be used to configure the entity. This method can be called multiple times for the same entity to perform various configuration lines.
3. HasKey
Configures the primary fundamental property(s) for this entity type.
4. HasMany
Configures many relationships from this entity type.
5. HasOptional
Configures an optional relationship from this entity type. Instances of the entity type will be able to be saved to the database without this relationship being specified, and the foreign key in the database will be nullable.
6. HasRequired
Configures a required relationship from this entity type. Instances of the entity type will not be able to be saved to the database unless this relationship is specified. The foreign key in the database will be non-nullable.
7. Ignore
Excludes a property from the model so that it will not be mapped to the database. (Inherited from StructuralTypeConfiguration)
8. Property
Configures a struct property that is defined on this type. (Inherited from StructuralTypeConfiguration)
9. ToTable(String)
Configures the table name that this entity type is mapped to.

Fluent API lets you configure your entities or their properties, whether you want to change something about how they map to the database or how they relate to one another. There's a massive variety of mappings and modeling that you can impact using the configurations. Following are the main types of mapping that Fluent API supports.

  • Entity Mapping
  • Properties Mapping

Entity Mapping

Entity mapping is just some simple mappings that will impact the Entity Framework's understanding of how the classes are mapped to the databases. All these we discussed in data annotations, and here we will see how to achieve the same things using Fluent API.

  • So rather than going into the domain classes to add these configurations, we can do this inside the context.
  • The first thing is to override the OnModelCreating method, which gives the modelBuilder to work with.

Default Schema

The default schema is dbo when the database is generated. You can use the HasDefaultSchema method on DbModelBuilder to specify the database schema for all tables, stored procedures, etc.

Map Entity to Table

With default convention, Code First will create the database tables with the name of DbSet properties in the context class such as Courses, Enrollments, and Students. But if you want different table names, you can override this convention and provide another table name other than the DbSet properties.

Entity Splitting (Map Entity to Multiple Table)

Entity Splitting lets you combine data from multiple tables into a single class, and it can only be used with tables that have a one-to-one relationship between them.

Properties Mapping

The Property method is used to configure attributes for each property belonging to an entity or complex type. The Property method obtains a configuration object for a given property. You can also map and configure the properties of your domain classes using Fluent API.

Configuring a Primary Key

The default convention for primary keys is −

  • Class defines a property whose name is “ID” or “Id”
  • The class name is followed by "ID" or "Id."

Configure Column

In Entity Framework, Code First will create a column for a property with the same name, order, and datatype.

Configure MaxLength Property

The Course Title property should be no longer than 24 characters in the following example. When the user specifies a value longer than 24 characters, the user will get a DbEntityValidationException exception.

Configuring Relationships

In the context of databases, a relationship exists between two relational database tables when one table has a foreign key that references the primary key of the other table. When working with Code First, you define your model by defining your domain CLR classes. By default, the Entity Framework uses the Code First conventions to map your courses to the database schema.

  • If you use the Code First naming conventions, in most cases, you can rely on Code First to set up relationships between your tables based on the foreign keys and navigation properties.
  • Suppose they don't meet up with those conventions. In that case, there are also configurations you can use to impact relationships between classes and how those relationships are realized in the database when you're adding configurations in Code First.
  • Some of them are available in the data annotations, and you can apply some even more complicated ones with a Fluent API.

Configure One-to-One Relationship

When you define a one-to-one relationship in your model, you use a reference navigation property in each class. Both tables can have only one record on either side of the relationship in the database. Each Primary key value relates to only one record (or no records) in the related table.

  • A one-to-one relationship is created if both of the related columns are primary keys or have unique constraints.
  • In a one-to-one relationship, the primary key acts additionally as a foreign key, and there is no separate foreign key column for either table.
  • This type of relationship is not common because most information related in this way would all be in one table.

Configure One-to-Many Relationship

The primary key table contains only one record that relates to none, one, or many records in the related table. This is the most commonly used type of relationship.

    In this type of relationship, a row in table A can have many matching rows in table B, but a row in table B can have only one matching row in table A.

    The foreign key is defined on the table representing the many ends of the relationship.

Configure Many-to-Many Relationship

Each record in both tables can relate to any number of records (or no records) in the other table.

  • You can create such a relationship by defining a third table, called a junction table, whose primary key consists of the foreign keys from table A and table B.
  • For example, the Student table and the Course table have a many-to-many relationship.