Configure Entity Mappings Using Fluent Api

In the last tutorial, we looked at how to use Fluent API in entity framework Code First. In this tutorial let us look at the how to configure the Entity mappings using Fluent API

Create the C# Console project as specified in this Entity Framework Code First tutorial.

 Entity Type Mapping

Entity Type Mapping

We are going to use the following domain class for this tutorial. The model has an Employee and Department class. It has an IgnoreThisTable class, which we do not want to include in the database. The ContactInfo is a Complextype class, which is referenced by both Employee and Department class.

Download the source code from github

Configuring the Entity Types

The configuration of the entity types is done using the generic method Entity<TEntityType> of the Dbmodelbuilder object. This method requires you to pass the entity type as the parameter. It returns the entitytypeconfiguration object which is then used to configure the entity. This class lives in assembly. System.Data.Entity.ModelConfiguration

Table Name

By Default Entity Framework uses the DbSet Property name to create the table Name. You can override this with the ToTable method of EntityTypeConfiguration object. The following code creates the mstEmployee Table for the employee Class

Table Schema

The “Totable” also has the second parameter, which takes the schema of the Table to be created. The example code is shown below creates the table with the schema admin instead of dbo.

Primary Key

You can configure the Primary key using the HasKey method of entityTypeConfiguration as shown below.

Composite Primary Key

Composite Primary Key can be created using the HasKey method as shown below

Ignore Property

Ignore method used to disable mapping of property to a column in the database. The Budget Property of Department table is not mapped to the database column in the following sample code

Ignore table

Ignore method of the modelBuilder class will exclude the database mapping for the type selected. The following code will ensure that the IgnoreThisTable is not created in the database.

Complex Type

Code First Convention detects a Complex type when it finds one. You can also specify the complextype in Fluent API using the ComplexType method as shown below.

The Final DbContext Class for the above examples is as shown below.


Download the source code from github

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top