Entity Framework Code First Approach

Entity Framework Code First Approach

In this article, I am going to give you a brief introduction to the Entity Framework Code First Approach. In the Entity Framework, the Code First Approach is one of the three approaches to interact with the database. The other two approaches are Model First Approach and Database First Approach. Here, in this article, we are going to keep the focus on the Code First Approach of Entity Framework and will learn how to use the Code First approach of Entity Framework to interact with the database.

Different Approaches to working with Entity Framework

As we already discussed, the Entity Framework provides three different approaches to work with and each approach has its own advantages and disadvantages. The three different approaches are as follows:

  1. Database First Approach: We need to use the Database First Approach if the database schema is already existing. In this approach, we generate the context and entities for the existing database using the Entity Data Model wizard. This approach is best suited for applications that use an already existing database.
  2. Code First Approach: We need to use this approach when we do not have an existing database for our application. In the Code-First Approach, we start creating our domain entities (domain classes) and context class first, and then based on the domain classes and context class, the entity framework will create the database.
  3. Model First Approach: This approach is very much similar to the Code First approach, but in this case, we use a visual EDMX designer to design our models. So, in this approach, we create the entities, relationships, and inheritance hierarchies directly on the visual designer and then generate entities, the context class, and the database script from your visual model.

Note: Please click here to learn more about the Development Approaches with Entity Framework in detail. In this article, we are going to keep the focus on Code First Approach. To learn the Database First Approach please check our previous section.

Entity Framework Code First Approach:

As already discussed, we need to use the Entity Framework Code First Approach when we do not have an existing database for our application. In this approach, we start developing our domain entities (domain classes) and context class first rather than designing the database first, and then based on the domain classes and context class, the entity framework will create the database. The following image shows the working style of Entity Framework Code First Approach. As you can see in the below image, the Entity Framework creates the database based on the domain classes and the context class. That means, in this approach, we need to start coding first in C#.NET or VB.NET and then Entity Framework API will create the database from your code.

Entity Framework Code First Approach

This approach is best suited for applications that are highly domain-centric and will have the domain model classes created first. The database here is needed only as a persistence mechanism for these domain models. That means Developers who follow the Domain-Driven Design (DDD) principles, prefer to begin coding with their domain classes first and then generate the database required to persist their data. So, in this case, the database is only for persisting the data.

Entity Framework Code-First Approach Workflow

The following diagram shows the workflow of the Entity Framework Code-First Approach. First, Create or modify domain classes, then configure these domain classes using Fluent-API or data annotation attributes, then create or update the database schema using automated migration or code-based migration. If these steps are not clear at the moment, then don’t worry we will understand all these steps in detail in our upcoming articles.

Entity Framework Code-First Approach Workflow

Few Important Points of EF Code First Approach:
  1. The Entity Framework Code First Approach targets a database that does not exist and Entity Framework Code First will create the database and related tables.
  2. Entity Framework Code First Approach can also be used with an empty database. In this case, Code First will add new tables to this empty existing database.
  3. It allows us to define our domain model using C# or VB.NET classes.
  4. It is also possible to provide additional configuration using attributes on our classes and properties or by using a fluent API. In our upcoming articles, we will discuss what additional information we can apply in detail.
Example to Understand Entity Framework Code-First Approach

First, you need to create your domain classes as per your business requirement. These domain classes have nothing to do with Entity Framework. They are just the classes of your business domain. The context class of Entity Framework manages the interaction between the domain classes and your database. The context is not specific to Code First. This is one of the important classes of Entity Framework and using this class we can interact with the database and perform the database CRUD Operations.

So, the Entity Framework Code-First Approach allows us to create our domain classes first, and based on those domain classes entity framework generates the database automatically for us. With this kept in mind, let us proceed and try to understand how to use Entity Framework Code-First step by step

Install Entity Framework:

The First step is to create a Console Application with the name EFCodeFirstDemo. To do so, open Visual Studio and then select File → New → Project from the context menu as shown in the below image.

Install Entity Framework

Next, select Visual C# from the left pane and Console Application from the middle template pane. Then provide the project name as EFCodeFirstDemo and choose the location where you want to create the project, and finally click on the OK button which will create the Console Application for us.

Example to Understand Entity Framework Code-First Approach

Next, we need to install EntityFramework.dll (EF API) in our Console Application Project in Visual Studio in order to work with the Entity Framework Code-First Approach. Here, we will install Entity Framework 6 API using NuGet Package Manager in Visual Studio. To do so, right-click on your project in the solution explorer and select Manage NuGet Packages… from the context menu as shown in the below image.

Example to Understand Entity Framework Code-First Approach

This will open the Manage NuGet Packages dialogue window. Select the Browse tab and then search for EntityFramework in the top left search box and press Enter. It will display all the API/Plug-ins starting with EntityFramework as shown in the below image.

Installing Entity Framework using Visual Studio

Now, select EntityFramework (which is provided by Microsoft). Also, select the latest version (in this case 6.4.4) or any version as per your requirement, and finally click on the Install button as shown in the below image.

Installing Entity Framework using Visual Studio

Once you click on the Install button, it will open the following License Acceptance dialogue box. Simply click on the I Accept button as shown in the below image.

Installing Entity Framework using Visual Studio

Once you click on the I Accept button, it will try to install Entity Framework API on your project and if it successfully installed the Entity Framework API, then you will get the following message in the output section of Visual Studio. Here, please make sure to select Package Manager from the output dropdown list.

Installing Entity Framework using Visual Studio

You can also check the version of EntityFramework.dll which is included in your project by going to the Reference folder. In the Reference folder, right-click on the EntityFramework and the click on the properties option. It will show the following details.

Installing Entity Framework using Visual Studio

The Installation of Entity Framework is completed and now, we are ready to use Entity Framework Code First Approach in our Console Application. The process is going to be the same for all other types of applications such as Windows Form, WCF, MVC, Web API, etc.

Using Entity Framework Code First Approach:

Let us understand how to use Entity Framework Code First Approach. Let us assume that we are creating a school application for some ABCD School. The users of this School application should have the ability to add and update students, standards, teachers, and course information.

Instead of designing the database tables first, let us start creating the domain classes as and when needed. Let us first create the Student and Standard classes where every Student is associated with one Standard representing one to one relationship and one standard can belongs to many students representing one-to-many relationships. Please click here to learn more about Entities Relationships in Entity Framework.

So, create a class file with the name Student.cs and then copy and paste the following code. As you can see, here, we are creating the Student class with few scalar properties as well as one Reference Navigation property called Standard which makes the relationship between Student and Standard entities one-to-one. In the next step, we are going to create the Standard entity.

using System;
namespace EFCodeFirstDemo
{
    public class Student
    {
        public int StudentId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime? DateOfBirth { get; set; }
        public byte[] Photo { get; set; }
        public decimal Height { get; set; }
        public float Weight { get; set; }

        public virtual Standard Standard { get; set; }
    }
}

Now, create a class file with the name Standard.cs and then copy and paste the following code. As you can see, here, we are creating the Standard class with few scalar properties as well as one collection Navigation property called Students which makes the relationship between Standard and Student entities one-to-many.

using System;
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; }
    }
}

Now, we are done with the initial domain classes for our school application. Later as we progress, we will add more domain classes in this example.

Creating the Context Class for Entity Framework Code First Approach:

The main class that coordinates Entity Framework functionality for a given data model is the database context class which allows to query and save data. Like the Entity Framework Database First Approach, the Entity Framework Code-First Approach also requires a user-defined context class which should be derived from DbContext class.

So, create a class file with the name EFCodeFirstContext.cs and then copy and paste the following code into it. You can give any name for your context. But the class should and must be derived from DbContext class and exposes DbSet properties for the types that you want to be part of the model. For example, Student and Standard domain classes in this case. The DbSet is a collection of entity classes (i.e. entity set). Here, we have given the property name in the plural form of the entity name like Students and Standards as it is recommended by Microsoft. The DbContext class belongs to System.Data.Entity namespace.

using System.Data.Entity;
namespace EFCodeFirstDemo
{
    public class EFCodeFirstContext: DbContext
    {
        //Constructor calling the DbContext class constructor
        public EFCodeFirstContext() : base()
        {
        }

        //Adding Domain Classes as DbSet
        public DbSet<Student> Students { get; set; }
        public DbSet<Standard> Standards { get; set; }
    }
}

As you can see in the above code, the parameterless constructor of our context class calls the DbContext Class constructor and this is required. We have already discussed these things in our EF Basics section. Also, we have included two classes as DbSet properties, and the entity framework going to create two database tables for the above two model classes with the required relationships.

So, we are done with the required model classes and context class for the Entity Framework Code-First Approach. Let us proceed further and add a new student using context class. So, modify the Main method of the Program class as follows:

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

Output: Student Added

If you are running for the first time, then it will take some time to create the database and tables, and then it is going to add the student to the Student database table.

Where the Database is Created?

Now, the question that should come to your mind is where is the database, and which are the database tables and their columns?

This is the beauty of the Entity Framework Code-First Approach. It will automatically create the database based on the parameter passed to the DBContext class constructor from your context class. As, we have not passed any parameter to the DBContext class constructor from our context class, so, it will create the database in the local SQLEXPRESS database as shown in the below image. It also automatically created the two database tables i.e. Students and Standards based on the Student and the Standard domain classes which are included as DbSet properties in the context class.

To see the local database, select SQL Server Object Explorer from the View menu in Visual Studio as shown in the below image.

Where the Database is Created?

This will open the following SQL Server Object Explorer window. Here, you can see the database name which is the same as the context class name, the database tables, and the corresponding columns.

Creating the Context Class for Entity Framework Code First Approach

As you can see in the above image, Entity Framework API created Students and Standards tables and each table contains columns with appropriate datatypes and lengths. The column names and datatype match with the properties of the respective domain classes. Further, if you notice it has also made StudentId and StandardId as primary keys and created the Standard_StandardId column as the foreign key. So, in this way, we can work with Entity Framework Code First Approach.

Note: Later I will show you how to generate the database in the SQL Server database instead of using the local DB.

Now, you might have one question on your mind how it has created columns with appropriate datatypes and length with Primary Keys and Foreign Keys? The answer is using code-first conventions. And that we will discuss in our next article.

In the next article, I am going to discuss the Default Code-First Conventions in Entity Framework with Examples. Here, in this article, I try to explain how to use Entity Framework Code First Approach and I hope you enjoyed this Introduction to Entity Framework Code First Approach 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 *