In this Entity Framework Fluent API Tutorial, we will look at how to configure the model classes using Fluent API in C#
We have seen how to configure our database using Code First conventions. Code First Convention maps our POCO classes to the database by making assumptions based on how the domain classes are written.
The database can be further configured using the data annotations attributes. These Attributes are applied to the class or property.
The Fluent API is another way to configure our domain classes. It is more flexible and provides developers with more power to configure the database.
Like us on Facebook
What is fluent API
A Fluent interface is a way of implementing an object oriented API in a way that aims to provide for more readable code Fluent interface resembles natural language making it easier to read and write. You can read about Fluent Interface from this link
Entity Framework Fluent API uses the Fluent Interface. Fluent API is implemented in DBModelbuilder class.
The Fluent API uses the DbModelbuilder class to map domain classes to a database schema. The reference to the DBModlebuilder class is obtained by overriding the OnModelCreating method of the DbContext object
This method is called before DBContext initialises the model. The initialization does not happen when the DBContext created. It happens when the Context is used for the first time. During the initialization, DBContext creates the DbModelBuilder instance. It then initialises all the domain classes. Then it calls the OnModelCreating Method and passes the reference to the DbModelBuilder
The OnModelCreating method can be overridden in our code as shown in the example below. We can then, get the reference to the DBModelbuilder in our overridden class. We can use DBModelBuilder along with the fluent API to configure our model.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
//Configure domain classes using modelBuilder here
DbModelBuilder class includes important properties and methods to configure the domain model.
Configurations : Returns the ConfigurationRegistrar object. You can use this object register the custom configuration. This helps us to move the configurations to different classes.
Conventions: Provides access to the conventions class of the DbModelBuilder. Using this property you can add/remove your own custom conventions.
Configure the model
Model-wide properties are applied on the entire model. The DbModelBuilder class exposes the following properties/methods to configure the model. Some of the important properties and methods are listed below
HasDefaultSchema : Configures the default database schema name to be used for the model. This can be overridden at the entity level
RegisterEntityType : Registers an entity type as part of the model.
Configuring the Entity
The configuration of the entity is done using the method Entity<TEntityType>. This method returns the entitytypeconfiguration object to configure the entities. Some of the important methods available in entitytypeconfiguration object are listed below
ToTable : Sets the table name for the entity type
HasKey : Configures the primary key for the selected entity type
HasMany : Configures a many relationship for the selected entity type
HasOptional : Configures an optional relationship for the selected entity type. Allows you save the Instances of the entity type to the database without this relationship being specified. This creates the nullable foreign key in the database
HasRequired : Configures a required relationship for the selected entity type. Does not allow you to save the Instances of the entity type without the relationship being specified . This creates not null foreign key in the database.
You can refer to Configure the Entity mappings Using Flunet API to find out how to use these methods
Configuring The Property
The EntityTypeConfiguration object, which is explained above returns the Property Method. This method is used to configure the attributes of the property of the selected entity.
The Property method returns the configuration object, which is specific to the type being configured. For Example calling property method on type, string will return StringPropertyConfiguration object. Similarly, property method returns DecimalPropertyConfiguration, BinaryPropertyConfiguration , DateTimePropertyConfiguration, PrimitivePropertyConfiguration is returned by the Property method depending on the type of the Property
Each of these PropertyConfiguration objects exposes methods to configure the Properties.
HasColumnName : Configures database column name of the property
HasColumnOrder : Configures the order in which the column appears in the database table. It is also used while creating the composite primary key to specify the key order.
HasColumnType : Configures the database column data type of the property
HasDatabaseGeneratedType : Configures how values for the property are generated by the database.
HasMaxLength : Specifies the maximum length of the property.
HasParameterName : Specifies the name of the parameter used in stored procedures for this property.
IsConcurrencyToken : Enables the property to be used in an optimistic concurrency updates.
IsFixedLength : Configures the property to be fixed length. Use HasMaxLength to set the length that the property is fixed to.
IsMaxLength : Configures the property to allow the maximum length supported by the database provider.
IsOptional : Specifies the database column as nullable.
IsReguired : Specifies the database column as non-nullable.
IsUnicode : Configures the property to support Unicode string content.
IsVariableLength : Configures the property to be variable length.
You can read How to Configure Property mappings using Fluent API to know more about how to use these methods.
In the next tutorials, we will show how to use Fluent API to configure the model, entity Type (Table), Property (Column) and relationships