Entity Configurations using Entity Framework Fluent API

Entity Configurations using Entity Framework Fluent API

In this article, I am going to discuss Entity Configurations using Entity Framework Fluent API with Examples. Please read our previous article where we discussed How to Configure Fluent API in Entity Framework Code First Approach with Examples.

Example to Understand Entity Configurations using Fluent API:

To understand Entity Configurations in Entity Framework Code First Approach using Fluent API, we are going to use the following Student and Standard Entities.

Student.cs
namespace EFCodeFirstDemo
{
    public class Student
    {
        public int StudentId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Branch { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Country { get; set; }
        public Standard Standard { get; set; }
    }
}
Standard.cs
using System.Collections.Generic;
namespace EFCodeFirstDemo
{
    public class Standard
    {
        public int StandardId { get; set; }
        public string StandardName { get; set; }
        public string Description { get; set; }
        public ICollection<Student> Students { get; set; }
    }
}

Please make sure to have the connection string with the name MyConnectionString within the app.config file or web.config file as shown in the below image.

Entity Configurations using Entity Framework Fluent API

Configure Default Schema using Entity Framework Fluent API

Let us understand how to configure the default schema for the tables in the database. However, it is also possible to change the schema while creating the individual tables. By default, the schema is created as dbo. For a better understanding, please modify the context class as follows.

using System.Data.Entity;
namespace EFCodeFirstDemo
{
    public class EFCodeFirstContext : DbContext
    {
        public EFCodeFirstContext() : base("name=MyConnectionString")
        {
            //Setting the Database Initializer as DropCreateDatabaseAlways
            Database.SetInitializer(new DropCreateDatabaseAlways<EFCodeFirstContext>());
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //Map Entity to Table
            modelBuilder.Entity<Student>().ToTable("StudentInfo"); //Default Schema will be dbo
            modelBuilder.Entity<Standard>().ToTable("StandardInfo"); //Default Schema will be dbo
        }

        public DbSet<Student> Students { get; set; }
        public DbSet<Standard> Standards { get; set; }
    }
}

Now, run the application code and verify the database schema and you should see the schema as dbo as shown in the below image.

Entity Configurations using Entity Framework Fluent API with Examples

Now, what our requirement is, instead of dbo, we want to set the default schema as Admin. To do so, we need to use the HasDefaultSchema method and to this method, we need to pass the default schema name. Now, modify the Context class as follows. In the below code, we have set Admin as a default schema.

using System.Data.Entity;
namespace EFCodeFirstDemo
{
    public class EFCodeFirstContext : DbContext
    {
        public EFCodeFirstContext() : base("name=MyConnectionString")
        {
            //Setting the Database Initializer as DropCreateDatabaseAlways
            Database.SetInitializer(new DropCreateDatabaseAlways<EFCodeFirstContext>());
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //Configure default schema
            modelBuilder.HasDefaultSchema("Admin");

            //Map Entity to Table
            modelBuilder.Entity<Student>().ToTable("StudentInfo"); //Default Schema will be Admin
            modelBuilder.Entity<Standard>().ToTable("StandardInfo"); //Default Schema will be Admin
        }

        public DbSet<Student> Students { get; set; }
        public DbSet<Standard> Standards { get; set; }
    }
}

Next, modify the Main method of the Program class as follows. Here, we are simply adding one student entity to the database.

using System;
namespace EFCodeFirstDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            using (EFCodeFirstContext context = new EFCodeFirstContext())
            {
                var student = new Student() { FirstName = "Pranaya", LastName = "Rout" };
                context.Students.Add(student);
                context.SaveChanges();
                Console.WriteLine("Student Added");
            }
            Console.ReadKey();
        }
    }
}

With the above changes in place, now run the application and verify the database. You will see that both the tables will be created with Admin schema as shown in the below image. Later in this article, I will explain how to specify a different schema explicitly.

Configure Default Schema using Entity Framework Fluent API

Map Entity to Table using Fluent API in Entity Framework

By default, the Entity Framework Code-First Approach will create the tables in the database with the name of DbSet properties in the context class. For example, modify the context class as follows. Here, we have included two DbSet Properties with the name Students and Standards.

using System.Data.Entity;
namespace EFCodeFirstDemo
{
    public class EFCodeFirstContext : DbContext
    {
        public EFCodeFirstContext() : base("name=MyConnectionString")
        {
        }
        public DbSet<Student> Students { get; set; }
        public DbSet<Standard> Standards { get; set; }
    }
}

In this case, the Entity Framework will create two tables in the database with the name Students and Standards as the DbSet Properties name are Students and Standards. We can override this default convention using Data Annotation Attribute and Fluent API. We have already discussed how to use the Table Data Annotation Attribute with Entity Framework Code First Approach. Now, let us understand how we can override the default convention using Entity Framework Fluent API.

How to Map Entity to Table using Fluent API in Entity Framework?

To Map Entity to Table using Entity Framework Fluent API, we need to use the ToTable method. There are two overloaded versions available of this method. One overloaded version takes the tableName as a parameter while the other overloaded method takes tableName and database schemaName as parameters.

How to Map Entity to Table using Fluent API in Entity Framework?

The above two methods configure the table name that this entity type is mapped to. If set the database schemaName, then it will create the table with that schema else it will create the table with the default schema.

So, modify the context class as follows to give a different table name than the DbSet properties name. Here, we need to override the onModelCreating method. In this case, even though the DbSet property names are Students and Standards, the Entity Framework is going to generate tables with the name StudentInfo and StandardInfo in the database. The point that you need to remember is that modelBuilder.Entity<TEntity>() returns the EntityTypeConfiguration object using which we can configure many things.

using System.Data.Entity;
namespace EFCodeFirstDemo
{
    public class EFCodeFirstContext : DbContext
    {
        public EFCodeFirstContext() : base("name=MyConnectionString")
        {
            //Setting the Database Initializer as DropCreateDatabaseAlways
            Database.SetInitializer(new DropCreateDatabaseAlways<EFCodeFirstContext>());
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //Map Entity to Table
            modelBuilder.Entity<Student>().ToTable("StudentInfo"); //Default Schema will be dbo
            modelBuilder.Entity<Standard>().ToTable("StandardInfo", "Admin"); // Schema will be Admin
        }

        public DbSet<Student> Students { get; set; }
        public DbSet<Standard> Standards { get; set; }
    }
}

As you can see in the above code, we start with the Entity<TEntity>() method. Most of the time, we have to start with the Entity<TEntity>() method to configure the Entity using Fluent API, and here we need to provide the Entity name for which we want to provide configuration. Then we used the ToTable() method to map the Student entity to the StudentInfo table and the Standard entity to the StandardInfo table. Here, the StandardInfo table will be created with the Admin schema because we have specified the Admin schema for the StandardInfo table and StudentInfo will be created with the default schema as we have not specified schema and in this case, the default schema will be dbo.

With the above changes in place, run the application and verify the database table and schema as shown in the below image. Here, you can see, the StudentInfo table is created with the default dbo schema and the StandardInfo table is created with the Admin schema.

Map Entity to Table using Fluent API in Entity Framework

How to Map one Entity to Multiple Tables using Entity Framework Fluent API?

Now, let us understand how to map one entity to multiple database tables using Entity Framework Fluent API. To do so using Entity Framework Fluent API, we need to use the Map method. The Map Method allows advanced configurations related to how this entity type will be mapped to the database schema. So, using the Map method, we can configure a few Properties of the Entity that will be mapped to one table and another few properties of the same Entity will be mapped to another table. It is not possible to map the same properties (no key peripeties) of an Entity in both the mapping table. And one more thing that you need to remember is specifying the key property in the property mapping is optional. By default, the key property will be available in both tables.

For a better understanding, please modify the context class as shown below to use the Map method. In the below example, we are mapping the Student entity to two database tables. Properties such as StudentId, FirstName, LastName, and Branch will be mapped to the StudentInfo database table. And properties such as StudentId, City, State, and Country will be mapped to the StudentAddress table. To Map the properties within the Map method we need to use the Properties method and to map to the table, we need to use the ToTable method.

using System.Data.Entity;
namespace EFCodeFirstDemo
{
    public class EFCodeFirstContext : DbContext
    {
        public EFCodeFirstContext() : base("name=MyConnectionString")
        {
            //Setting the Database Initializer as DropCreateDatabaseAlways
            Database.SetInitializer(new DropCreateDatabaseAlways<EFCodeFirstContext>());
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //Map one Entity to Multiple Tables
            modelBuilder.Entity<Student>()
                .Map(m =>
                {
                    //Set the Properties of table using Properties Method
                    m.Properties(p => new { p.StudentId, p.FirstName, p.LastName, p.Branch });
                    //Set the Table Name using ToTable Method
                    m.ToTable("StudentInfo");
                })
                .Map(m => {
                    //Set the Properties of table using Properties Method
                    m.Properties(p => new { p.StudentId, p.City, p.State, p.Country });
                    //Set the Table Name using ToTable Method
                    m.ToTable("StudentAddress");
            });

            //Map Entity to Table
            modelBuilder.Entity<Standard>().ToTable("StandardInfo");
        }

        public DbSet<Student> Students { get; set; }
        public DbSet<Standard> Standards { get; set; }
    }
} 

As you can see in the above code, within the Map method, we have mapped some properties of the Student entity to the StudentInfo table and other properties to the StudentInfoAddress table. Now, with the above changes in place, run the application and verify the database. In this case, you should the StudentInfo and StudentInfoAddress tables with the required columns as shown in the below image.

How to Map one Entity to Multiple Tables using Entity Framework Fluent API?

Note: When you add one student entity using the context class, then the data will be stored in the above two database tables based on the properties. The StudentId, FirstName, LastName, and Branch values will be stored in the StudentInfo table and the values StudentId, City, State, and Country will be stored in the StudentAddress table.

Note: Using the Map method, we cannot Map the reference type properties. If we try then we will get System.InvalidOperationException saying ‘The property ‘Standard’ on type ‘Student’ cannot be mapped because it has been explicitly excluded from the model or it is of a type not supported by the DbModelBuilderVersion being used.

In the next article, I am going to discuss Property Configurations using Fluent API in Entity Framework with Examples. Here, in this article, I try to explain Entity Mappings using Fluent API in Entity Framework with Examples. I hope you enjoyed this Entity Configurations using Entity Framework Fluent API article. Please give your valuable feedback and suggestions about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *