The Entity Framework

The Entity Framework is the Object Relational Mapping (ORM) framework that enables developers to work on domain-specific objects directly for data access instead of working on database queries. This reduces a lot of the code complexity in the data access layer in the application.

Before discussing the Entity Framework and its features, let us pause for a moment and think about the steps that we follow when we try to save some information to the database when using ADO.NET:

  1. Construct the business domain object.
  2. Create a connection to your database.
  3. Open the connection.
  4. Create a command object along with the command type.
  5. Add the properties of your business domain object to the parameters of the command object.
  6. Execute the command that saves the data into the database.

We have to follow the previously mentioned six steps for common operations such as saving a piece of data into the database.

If you are using an ORM framework such as the Entity Framework, you just need three steps:

  1. Construct the business domain object.
  2. Create the DbContext class for your business domain object. The instance of the DbContext class represents the session with the database.
  3. Save it to the database using the instance of the DBContext class.

You might wonder how that is possible.

As a matter of fact, in the background, the Entity Framework creates a connection to the database and executes the query to save the business domain object to the database. To make it simple, the Entity Framework writes all the data access code for you so that you can concentrate on achieving the business functionality of the application rather than writing the database layer code.

The Entity Framework is independent of ASP.NET MVC

As discussed earlier, the Entity Framework is an ORM framework for accessing data and is independent of ASP.NET MVC. The Entity Framework could be used in Windows Communication Foundation (WCF) services, Web API services, and even in console applications. You could use the Entity Framework in any type of application and make use of it to access data using objects. The concepts and the functionalities of the Entity Framework remain the same, irrespective of the type of application that you use it with.

Now, we are going to use the Entity Framework with the console application. This allows us to concentrate on the task at hand and demonstrate the functionalities of the Entity Framework instead of working on the boilerplate code of the ASP.NET Core application. In a later part of this chapter, we will integrate the Entity Framework with the ASP.NET Core application.

The latest version of the Entity Framework for the SQL server is 7.0.0 and it is still in beta at the time of writing this book. EF7 (Entity Framework 7) brings significant changes when compared to its previous version (Entity Framework 6). However, EF7 is the recommended version when building ASP.NET 5 applications and hence we will be using this version in this book.

Note

We need a database to explain many of the features of the Entity Framework. Please install SQL Server 2014 Express on your PC before continuing further. Step by step instructions for installing SQL Server 2014 Express and SQL Server Management Studio is given in Appendix A.

Creating console applications with the Entity Framework

Follow these steps to create a simple console application:

  1. Select File | New Project and select Console Application.
  2. Name the project and click on OK.

    Creating console applications with the Entity Framework

Installing the Entity Framework 7 NuGet package

There are two ways to install any NuGet package in your application:

  • Using the NuGet Package Manager
  • Using Package Manager Console

Using the NuGet Package Manager

People who prefer graphical interfaces can use this option:

  1. Right-click on the console project and select Manage NuGet Packages from the context menu:

    Using the NuGet Package Manager

  2. Search for EntityFramework.MicrosoftSqlServer in the NuGet package and make sure the Include prerelease checkbox is checked. Click on Install once you select EntityFramework.MicrosoftSqlServer and select Latest pre-release 7.0.0-rc1-final (at the time of writing this book). You can select any latest version of Entity Framework 7:

    Using the NuGet Package Manager

  3. Once you click on Install, the NuGet package manager will ask you to review the changes. Click on OK:

    Using the NuGet Package Manager

  4. Click on I Accept in the License Acceptance window:

    Using the NuGet Package Manager

  5. Once you click on I Accept, it will install the Entity Framework with all its dependencies. In the Output window, you will get the Finished message once the installation is complete:

    Using the NuGet Package Manager

Using the Package Manager Console

To install the NuGet package using the Package Manager Console, follow these steps:

  1. Open the Package Manager Console window by selecting the menu option View | Other Windows | Package Manager Console.

    Using the Package Manager Console

  2. Type Install-Package EntityFramework.MicrosoftSqlServer - Pre in the Package Manager Console window as shown in the following screenshot:

    Using the Package Manager Console

  3. Once the installation is complete, a message, Successfully installed 'EntityFramework.MicrosoftSqlServer 7.0.0-rc1-final', will be shown:

    Using the Package Manager Console

Installing Entity Framework commands

We need to install the Entity Framework commands package in order to perform migration activities. Migration includes the creation of a database and its associated tables. Any changes in the schema will also be taken care of by migration:

Installing Entity Framework commands

As discussed earlier, we need to follow three steps in order to interact with the database when we are using the Entity Framework:

  1. Create the Model classes.
  2. Create the DbContext class for your business domain object. The instance of the DbContext class represents the session with the database.
  3. Construct the business domain object and save it to the database using the instance of the DBContext class.

Let us discuss each of the preceding steps in details and try to save an object to the database.

Creating Model classes

The Model classes are simple POCO objects, which can be used with the Entity Framework.

Let us create a POCO class for our business domain object, the Employee class in our case. I have created a new file named Employee.cs in our console application with the following content. This Employee class contains a few properties of an employee and has no special properties or fields to make it work with the Entity Framework.

Let's take a look at the following code snippet:

public class Employee { 
  public int EmployeeId { get; set; } 
  public string Name { get; set; } 
  public decimal Salary { get; set; } 
  public string Designation { get; set; } 
} 

By convention, if the property name is Id or ClassName+Id, it will be considered as a primary key by Entity Framework while creating the database table.

Properties with string data types will be created as fields of the type nvarchar(max). However, we can override this behavior by using annotations, which we will be discussed later.

Creating the DbContext class

The instance of the DbContext class represents the session to the database and this DbContext class does most of the heavy lifting of your data access for your application.

Create a new class by the named EmployeeDbContext with the following content:

using Microsoft.Data.Entity; 
using System.Configuration; 
 
namespace ConsoleEF7 { 
  public class EmployeeDbContext : DbContext{ 
    public DbSet<Employee> Employees {get; set;} 
 
    protected override void OnConfiguring(DbContextOptionsBuilder      optionsBuilder) {string connectionString =        ConfigurationManager.ConnectionStrings       ["SqlServerExpress"].ConnectionString; 
      optionsBuilder.UseSqlServer(connectionString); 
      base.OnConfiguring(optionsBuilder); 
    } 
  } 
} 

Configure it using App.Config:

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
  <startup> 
    <supportedRuntime version="v4.0"  
    sku=".NETFramework,Version=v4.6.1" /> 
  </startup> 
  <connectionStrings> 
    <add name="SqlServerExpress" connectionString="Data Source=     MUGIL-PCSQLEXPRESS;Initial Catalog=EF7Console;Integrated      Security=True"/> 
  </connectionStrings> 
</configuration> 

There are a few things to be noted in the preceding code snippet:

  • Include the Microsoft.Data.Entity namespace as the DbContext class available in this namespace. Our connection string is available in the App.Config file. In order to read the contents of the App.Config file, we are including the ConfigurationManager class in System.Configuration.
  • In order to use the DbContext API, a class has to be created which inherits from the DbContext class so that we can access methods of the DbContext API. We have created the EmployeeDbContext class which was inherited from DbContext class.
  • DbSet is a class which allows operations of the Entity Framework to be performed for a given Entity type. We need to create the DbSet object for each of the Entity types that we use in our application. In this example, we are using only one DbSet object as we are working with the Employee class.

Create a migration

Migration is the process of recording all the changes of your database. Add-Migration is the Entity Framework command for adding migration:

Create a migration

  1. Once you add the migration, you can revoke the changes by executing the  Remove-Migration Entity Framework command.

    Create a migration

    • This is what the migrations directory looks like:

      Create a migration

  2. Update the database by issuing the Entity Framework command Update-Database , which updates the database tables as per the information available in the migration. As we have installed the EntityFramework.Commands package earlier, these commands will be available for the application:

    Create a migration

  3. Once you update the database, you can see the changes in the database by connecting to SQL Server Management Studio:

    Create a migration

  4. Perform the database operation to save the business domain object in the database. You can create the database manually or, if the database is not available, it will create one for you.

The Main method is updated with the following code:

class Program { 
  static void Main(string[] args) { 
    AddEmployee(); 
  } 
 
  static void AddEmployee() { 
    using (var db = new EmployeeDbContext()) { 
      Employee employee= new Employee { 
        Designation = "Software Engineer", 
        Name = "Scott", 
        Salary = 5600 
      }; 
 
      db.Employees.Add(employee); 
      int recordsInserted = db.SaveChanges(); 
      Console.WriteLine("Number of records inserted:" +        recordsInserted); 
      Console.ReadLine();
    } 
  } 
} 

Firstly, we are constructing the business domain object. Then, we are adding the constructed Employee object to the employee's DbSet of the DbContext class. Finally, we are calling the SaveChanges method DbContext API, which will save all the pending changes to the database.

You might be wondering how it can save it to the database when we have not even given the connection string.

Let us discuss what happens behind the scenes when we run the program:

  • When you make changes to any of the DbSet collection, the Entity Framework checks whether the database exists. If it does not exist, it creates a new one using the pattern <Namespace of DbContextName>. In our case, a database called by EF6.EmployeeDbContext would be created.
  • Then, it creates database tables for the entities declared in DbSet. By convention, the Entity Framework uses the pluralized form of Entity for the table names. As we have declared DbSet for the Employee entity, the Entity Framework creates a pluralized form of Employee and creates the table named Employees.

The creation of the database and tables happens when the following code is executed:

db.Employees.Add(employee); 

When SaveChanges method is executed, the data in the Employee object will get saved to the database and returns the number of records affected. In the preceding case, it returns 1.

When you run the application again, the first two steps mentioned previously will be skipped as the database and table will have already been created.

When you query the database, you can see the newly inserted record:

Create a migration

How the SaveChanges method works

When we are making changes, the Entity Framework tracks the state of each of the objects and executes the appropriate query when SaveChanges method is called.

For example, when we add an Employee object to the employees' collection (DbSet), this object is being tracked as Entity in the Added state. When SaveChanges is called, the Entity Framework creates an insert query for the same and executes it. The same is the case with updating and deleting the object. The Entity Framework sets the Entity state of the respective objects to Modified and Deleted. When SaveChanges is called, it creates and executes the Update and Delete queries.

How the SaveChanges method works

The preceding figure explains how the SaveChanges method works at a high-level for different types of change. We have a couple of POCO objects (Object 1 and Object 2), which have been added to the employees' DbSet object. Let us assume Object 3 and Object 4 have been modified and objects Object 5 and Object 6 are in Deleted state. When you call SaveChanges method, it creates three sets of queries. The first set of queries is for the addition of objects, resulting in insert queries getting executed against the database. In the second set of queries, Update queries are created and executed for the objects whose state is modified. Finally, Delete queries are executed for the objects for all the Deleted state objects.

Updating the record

Let us try to update the salary of an inserted employee record using the Entity Framework:

static void UpdateSalary() { 
  using (var db = new EmployeeDbContext()){ 
    Employee employee = db.Employees.Where(emp => emp.EmployeeId      == 1).FirstOrDefault(); 
    if(employee!=null){
      employee.Salary = 6500; 
      int recordsUpdated = db.SaveChanges(); 
      Console.WriteLine("Records updated:" + recordsUpdated); 
      Console.ReadLine(); 
    }
  } 
} 

In the preceding method, we find the employee with EmployeeId = 1. Then, we update the salary of the employee to 6500 and save the employee object to the database. Please note that, in the preceding method, we interact with the database a couple of times—once to find the correct employee record (read operation) and again to update the record (update operation).

static void Main(string[] args){
  UpdateSalary(); 
} 

The Main method is updated to call the UpdateSalary method. When you query the database, you should see the record with the updated information:

Updating the record

Deleting the record

Deleting the record is a bit tricky as it involves setting the state directly. In the following method, firstly we get the object and setting the state of the object to Deleted. Then calling the SaveChanges method will generate the delete query for the object and execute it, which in turn will eventually delete the record in the database:

static void DeleteEmployee() { 
  using (var db = new EmployeeDbContext()) { 
    Employee employeeToBeDeleted = db.Employees.Where(emp =>      emp.EmployeeId == 1).FirstOrDefault(); 
    if (employeeToBeDeleted != null) { 
      db.Entry(employeeToBeDeleted).State =        Microsoft.Data.Entity.EntityState.Deleted; 
      int recordsDeleted = db.SaveChanges(); 
      Console.WriteLine("Number of records deleted:" +        recordsDeleted); 
      Console.ReadLine(); 
    } 
  } 
} 
 
static void Main(string[] args) { 
  DeleteEmployee(); 
} 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset